Skip to content

Commit 03a0c25

Browse files
authored
clean up (#8)
* Add websocket listener * Add auth to websocket connection * clean up
1 parent 518c9a8 commit 03a0c25

3 files changed

Lines changed: 41 additions & 75 deletions

File tree

openevsehttp/__init__.py

Lines changed: 38 additions & 74 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
import logging
77
from typing import Optional
88

9-
import aiohttp
9+
import aiohttp # type: ignore
1010
import requests # type: ignore
1111

1212
from .const import MAX_AMPS, MIN_AMPS
@@ -53,16 +53,7 @@ def __init__(
5353
user=None,
5454
password=None,
5555
):
56-
"""Initialize a OpenEVSEWebsocket instance.
57-
Parameters:
58-
server (openevse address):
59-
A connected instance.
60-
callback (Runnable):
61-
Called when interesting events occur. Provides arguments:
62-
msgtype (str): Message type or SIGNAL_* constant
63-
data (str): Current STATE_* or websocket payload contents
64-
error (str): Error message if any or None
65-
"""
56+
"""Initialize a OpenEVSEWebsocket instance."""
6657
self.session = aiohttp.ClientSession()
6758
self.uri = self._get_uri(server)
6859
self._user = (user,)
@@ -89,74 +80,47 @@ def state(self, value):
8980
@staticmethod
9081
def _get_uri(server):
9182
"""Generate the websocket URI."""
92-
return server._url("/:/ws").replace("http", "ws")
83+
return server.url("/:/ws").replace("http", "ws")
9384

9485
async def running(self):
9586
"""Open a persistent websocket connection and act on events."""
9687
self.state = STATE_STARTING
88+
auth = None
89+
90+
if self._user and self._password:
91+
auth = aiohttp.BasicAuth(self._user, self._password)
9792

9893
try:
99-
if self._user and self._password:
100-
async with self.session.ws_connect(
101-
self.uri,
102-
heartbeat=15,
103-
auth=aiohttp.BasicAuth(self._user, self._password),
104-
) as ws_client:
105-
self.state = STATE_CONNECTED
106-
self.failed_attempts = 0
107-
108-
async for message in ws_client:
109-
if self.state == STATE_STOPPED:
110-
break
111-
112-
if message.type == aiohttp.WSMsgType.TEXT:
113-
msg = message.json()
114-
msgtype = msg["type"]
115-
116-
if msgtype not in self.subscriptions:
117-
_LOGGER.debug("Ignoring: %s", msg)
118-
continue
119-
120-
else:
121-
self.callback(msgtype, msg, None)
122-
123-
elif message.type == aiohttp.WSMsgType.CLOSED:
124-
_LOGGER.warning("AIOHTTP websocket connection closed")
125-
break
126-
127-
elif message.type == aiohttp.WSMsgType.ERROR:
128-
_LOGGER.error("AIOHTTP websocket error")
129-
break
130-
else:
131-
async with self.session.ws_connect(
132-
self.uri,
133-
heartbeat=15,
134-
) as ws_client:
135-
self.state = STATE_CONNECTED
136-
self.failed_attempts = 0
94+
async with self.session.ws_connect(
95+
self.uri,
96+
heartbeat=15,
97+
auth=auth,
98+
) as ws_client:
99+
self.state = STATE_CONNECTED
100+
self.failed_attempts = 0
137101

138-
async for message in ws_client:
139-
if self.state == STATE_STOPPED:
140-
break
102+
async for message in ws_client:
103+
if self.state == STATE_STOPPED:
104+
break
141105

142-
if message.type == aiohttp.WSMsgType.TEXT:
143-
msg = message.json()
144-
msgtype = msg["type"]
106+
if message.type == aiohttp.WSMsgType.TEXT:
107+
msg = message.json()
108+
msgtype = msg["type"]
145109

146-
if msgtype not in self.subscriptions:
147-
_LOGGER.debug("Ignoring: %s", msg)
148-
continue
110+
if msgtype in self.subscriptions:
111+
self.callback(msgtype, msg, None)
149112

150-
else:
151-
self.callback(msgtype, msg, None)
113+
else:
114+
_LOGGER.debug("Ignoring: %s", msg)
115+
continue
152116

153-
elif message.type == aiohttp.WSMsgType.CLOSED:
154-
_LOGGER.warning("AIOHTTP websocket connection closed")
155-
break
117+
elif message.type == aiohttp.WSMsgType.CLOSED:
118+
_LOGGER.warning("Websocket connection closed")
119+
break
156120

157-
elif message.type == aiohttp.WSMsgType.ERROR:
158-
_LOGGER.error("AIOHTTP websocket error")
159-
break
121+
elif message.type == aiohttp.WSMsgType.ERROR:
122+
_LOGGER.error("Websocket error")
123+
break
160124

161125
except aiohttp.ClientResponseError as error:
162126
if error.code == 401:
@@ -208,14 +172,14 @@ def __init__(self, host: str, user: str = None, pwd: str = None) -> None:
208172
"""Connect to an OpenEVSE charger equipped with wifi or ethernet."""
209173
self._user = user
210174
self._pwd = pwd
211-
self._url = f"http://{host}"
175+
self.url = f"http://{host}"
212176
self._status = None
213177
self._config = None
214178
self._override = None
215179

216180
def send_command(self, command: str) -> tuple | None:
217181
"""Send a RAPI command to the charger and parses the response."""
218-
url = f"{self._url}/r"
182+
url = f"{self.url}/r"
219183
data = {"json": 1, "rapi": command}
220184

221185
_LOGGER.debug("Posting data: %s to %s", command, url)
@@ -238,7 +202,7 @@ def send_command(self, command: str) -> tuple | None:
238202

239203
def update(self) -> None:
240204
"""Update the values."""
241-
urls = [f"{self._url}/status", f"{self._url}/config"]
205+
urls = [f"{self.url}/status", f"{self.url}/config"]
242206

243207
for url in urls:
244208
_LOGGER.debug("Updating data from %s", url)
@@ -258,7 +222,7 @@ def update(self) -> None:
258222

259223
def get_override(self) -> None:
260224
"""Get the manual override status."""
261-
url = f"{self._url}/overrride"
225+
url = f"{self.url}/overrride"
262226

263227
_LOGGER.debug("Geting data from %s", url)
264228
if self._user is not None:
@@ -282,7 +246,7 @@ def set_override(
282246
auto_release: bool = True,
283247
) -> str:
284248
"""Set the manual override status."""
285-
url = f"{self._url}/overrride"
249+
url = f"{self.url}/overrride"
286250

287251
if state not in ["active", "disabled"]:
288252
raise ValueError
@@ -310,7 +274,7 @@ def set_override(
310274

311275
def toggle_override(self) -> None:
312276
"""Toggle the manual override status."""
313-
url = f"{self._url}/overrride"
277+
url = f"{self.url}/overrride"
314278

315279
_LOGGER.debug("Toggling manual override %s", url)
316280
if self._user is not None:
@@ -328,7 +292,7 @@ def toggle_override(self) -> None:
328292

329293
def clear_override(self) -> None:
330294
"""Clear the manual override status."""
331-
url = f"{self._url}/overrride"
295+
url = f"{self.url}/overrride"
332296

333297
_LOGGER.debug("Clearing manual overrride %s", url)
334298
if self._user is not None:

pylintrc

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,8 @@ disable=
2626
too-many-public-methods,
2727
too-many-instance-attributes,
2828
too-many-branches,
29-
no-self-use
29+
no-self-use,
30+
too-many-statements
3031

3132
[REPORTS]
3233
score=no

requirements_test.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,4 @@ pytest==6.2.4
22
pytest-cov==2.12.1
33
pytest-timeout==1.4.2
44
requests_mock
5+
aiohttp

0 commit comments

Comments
 (0)