Skip to content

Commit

Permalink
fix: add exception class and error throw code (#25)
Browse files Browse the repository at this point in the history
  • Loading branch information
miettal authored Nov 4, 2024
1 parent c4b623d commit 0359fe6
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 24 deletions.
1 change: 1 addition & 0 deletions openems/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
"""OpenEMS."""
from . import api # noqa
from . import exceptions # noqa
82 changes: 58 additions & 24 deletions openems/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,14 @@
import asyncio
import uuid

import jsonrpc_base

from jsonrpc_websocket import Server

import pandas as pd

from . import exceptions


class OpenEMSAPIClient():
"""OpenEMS API Client Class."""
Expand All @@ -20,28 +24,46 @@ async def login(self):
"""login."""
server = Server(self.server_url)
await server.ws_connect()
await server.authenticateWithPassword(username=self.username, password=self.password)
try:
await server.authenticateWithPassword(username=self.username, password=self.password)
except jsonrpc_base.jsonrpc.ProtocolError as e:
if type(e.args) is tuple:
raise exceptions.APIError(message=f'{e.args[0]}: {e.args[1]}', code=e.args[0])
else:
raise e
return server

def get_edges(self):
"""Call getEdges API."""
async def f():
server = await self.login()
r = await server.getEdges(page=0, limit=20, searchParams={})
try:
r = await server.getEdges(page=0, limit=20, searchParams={})
except jsonrpc_base.jsonrpc.ProtocolError as e:
if type(e.args) is tuple:
raise exceptions.APIError(message=f'{e.args[0]}: {e.args[1]}', code=e.args[0])
else:
raise e
return r['edges']
return asyncio.run(f())

def get_edge_config(self, edge_id):
"""Call getEdgeConfig API."""
async def f():
server = await self.login()
r_edge_rpc = await server.edgeRpc(edgeId=edge_id, payload={
'jsonrpc': '2.0',
'method': 'getEdgeConfig',
'params': {
},
'id': str(uuid.uuid4()),
})
try:
r_edge_rpc = await server.edgeRpc(edgeId=edge_id, payload={
'jsonrpc': '2.0',
'method': 'getEdgeConfig',
'params': {
},
'id': str(uuid.uuid4()),
})
except jsonrpc_base.jsonrpc.ProtocolError as e:
if type(e.args) is tuple:
raise exceptions.APIError(message=f'{e.args[0]}: {e.args[1]}', code=e.args[0])
else:
raise e
r = r_edge_rpc['payload']['result']
return r
return asyncio.run(f())
Expand All @@ -61,12 +83,18 @@ async def f():
'value': resolution_sec,
'unit': 'SECONDS',
}
r_edge_rpc = await server.edgeRpc(edgeId=edge_id, payload={
'jsonrpc': '2.0',
'method': 'queryHistoricTimeseriesData',
'params': params,
'id': str(uuid.uuid4()),
})
try:
r_edge_rpc = await server.edgeRpc(edgeId=edge_id, payload={
'jsonrpc': '2.0',
'method': 'queryHistoricTimeseriesData',
'params': params,
'id': str(uuid.uuid4()),
})
except jsonrpc_base.jsonrpc.ProtocolError as e:
if type(e.args) is tuple:
raise exceptions.APIError(message=f'{e.args[0]}: {e.args[1]}', code=e.args[0])
else:
raise e
r = r_edge_rpc['payload']['result']
df = pd.DataFrame(r['data'], index=r['timestamps'])
df.index.name = 'Time'
Expand All @@ -78,15 +106,21 @@ def update_component_config(self, edge_id, component_id, properties):
"""Call edgeRpc.updateComponentConfig API."""
async def f():
server = await self.login()
r_edge_rpc = await server.edgeRpc(edgeId=edge_id, payload={
'jsonrpc': '2.0',
'method': 'updateComponentConfig',
'params': {
'componentId': component_id,
'properties': properties,
},
'id': str(uuid.uuid4()),
})
try:
r_edge_rpc = await server.edgeRpc(edgeId=edge_id, payload={
'jsonrpc': '2.0',
'method': 'updateComponentConfig',
'params': {
'componentId': component_id,
'properties': properties,
},
'id': str(uuid.uuid4()),
})
except jsonrpc_base.jsonrpc.ProtocolError as e:
if type(e.args) is tuple:
raise exceptions.APIError(message=f'{e.args[0]}: {e.args[1]}', code=e.args[0])
else:
raise e
r = r_edge_rpc['payload']['result']
return r
return asyncio.run(f())
Expand Down
10 changes: 10 additions & 0 deletions openems/exceptions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
"""openems.exceptions."""


class APIError(Exception):
"""HTTPError Exception Class."""

def __init__(self, message: str, code: int):
"""__init__."""
super().__init__(message)
self.code = code

0 comments on commit 0359fe6

Please sign in to comment.