Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
catduckgnaf committed Mar 6, 2024
2 parents d8ac952 + 03c090d commit 1c81d9c
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 26 deletions.
30 changes: 16 additions & 14 deletions custom_components/ryobi_gdo/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
from collections import abc
import json
import logging
from typing import Any

import aiohttp # type: ignore
from aiohttp.client_exceptions import ServerConnectionError, ServerTimeoutError
Expand Down Expand Up @@ -81,7 +80,7 @@ def __init__(self, username: str, password: str, device_id: str | None = None):

async def _process_request(
self, url: str, method: str, data: dict[str, str]
) -> Optional[dict]:
) -> dict | None:
"""Process HTTP requests."""
async with aiohttp.ClientSession() as session:
http_hethod = getattr(session, method)
Expand All @@ -95,9 +94,7 @@ async def _process_request(
if not isinstance(reply, dict):
reply = None
except ValueError:
LOGGER.warning(
"Reply was not in JSON format: %s", rawReply
)
LOGGER.warning("Reply was not in JSON format: %s", rawReply)

if response.status in [404, 405, 500]:
LOGGER.warning("HTTP Error: %s", rawReply)
Expand Down Expand Up @@ -232,9 +229,9 @@ async def update(self) -> bool:
"micEnable"
]["value"]
if "fan" in self._modules:
self._data["fan"] = dtm[self._modules["fan"]]["at"][
"speed"
]["value"]
self._data["fan"] = dtm[self._modules["fan"]]["at"]["speed"][
"value"
]

if "name" in request["result"][0]["metaData"]:
self._data["device_name"] = request["result"][0]["metaData"]["name"]
Expand All @@ -260,7 +257,7 @@ async def _index_modules(self, dtm: dict) -> bool:
"parkAssistLaser",
"inflator",
"btSpeaker",
"fan"
"fan",
]
frame = {}
try:
Expand Down Expand Up @@ -288,7 +285,7 @@ def get_module_type(self, module: str) -> int:
"parkAssistLaser": 1,
"inflator": 4,
"btSpeaker": 2,
"fan": 3
"fan": 3,
}
return module_type[module]

Expand Down Expand Up @@ -339,6 +336,7 @@ async def _process_message(
"Websocket callback msg_type: %s msg: %s err: %s", msg_type, msg, error
)
if msg_type == SIGNAL_CONNECTION_STATE:
self.ws_listening = False
if msg == STATE_CONNECTED:
LOGGER.debug("Websocket to %s successful", self.ws.url)
self.ws_listening = True
Expand All @@ -347,7 +345,6 @@ async def _process_message(
"Websocket to %s disconnected",
self.ws.uri,
)
self.ws_listening = False
# Stopped websockets without errors are expected during shutdown
# and ignored
elif msg == STATE_STOPPED and error:
Expand All @@ -356,7 +353,10 @@ async def _process_message(
self.ws.url,
error,
)
self.ws_listening = False
# Flag websocket as not listening
# STATE_STOPPED with no error
else:
LOGGER.debug("Websocket state: %s error: %s", msg, error)

elif msg_type == "data":
message = msg
Expand Down Expand Up @@ -384,6 +384,8 @@ async def _process_message(

else:
LOGGER.error("Websocket unknown message received: %s", message)
else:
LOGGER.debug("Unknown message from websocket: %s type: %s", msg, msg_type)

async def parse_message(self, data: dict) -> None:
"""Parse incoming updated data."""
Expand Down Expand Up @@ -554,8 +556,8 @@ async def running(self):
if self._state != STATE_STOPPED:
LOGGER.debug(
"Websocket msgType: %s CloseCode: %s",
str(aiohttp.WSMsgType),
str(aiohttp.WSCloseCode),
str(aiohttp.WSMsgType.name),
str(aiohttp.WSCloseCode.name),
)
await RyobiWebSocket.state.fset(self, STATE_DISCONNECTED)
await asyncio.sleep(5)
Expand Down
21 changes: 10 additions & 11 deletions custom_components/ryobi_gdo/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,32 +42,31 @@ async def _async_update_data(self):
result = await self.client.update()
if result:
self._data = self.client._data
await self._websocket_check()
return self._data
raise UpdateFailed()

async def send_command(self, device: str, command: str, value: bool):
"""Send command to GDO."""
# Websocket dropped out handle reconnecting
if not self.client.ws_listening:
# Close any left over sessions
await self.client.ws_disconnect()
# Reconnect the websocket
await self.client.ws_connect()
await self._websocket_check()
module = self.client.get_module(device)
module_type = self.client.get_module_type(device)
data = (module, module_type, command, value)
await self.client.ws.send_message(*data)

@callback
async def websocket_update(self):
"""Trigger processing updated websocket data."""
LOGGER.debug("Processing websocket data.")
# Websocket dropped out handle reconnecting
async def _websocket_check(self):
"""Handle reconnection of websocket."""
if not self.client.ws_listening:
# Close any left over sessions
await self.client.ws_disconnect()
# Reconnect the websocket
await self.client.ws_connect()

@callback
async def websocket_update(self):
"""Trigger processing updated websocket data."""
LOGGER.debug("Processing websocket data.")
await self._websocket_check()
self._data = self.client._data
coordinator = self.hass.data[DOMAIN][self.config.entry_id][COORDINATOR]
coordinator.async_set_updated_data(self._data)
2 changes: 1 addition & 1 deletion requirements-test.txt
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,5 @@ pytest>=7.2
pytest-cov>=3.0
pytest-homeassistant-custom-component>=0.12
tzdata
ruff~=0.2
ruff~=0.3
aioresponses

0 comments on commit 1c81d9c

Please sign in to comment.