Skip to content

Commit a29306a

Browse files
committed
clean up
1 parent c2b5d04 commit a29306a

File tree

3 files changed

+24
-15
lines changed

3 files changed

+24
-15
lines changed

zha/application/gateway.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -911,7 +911,7 @@ def __init__(self, config: ZHAData) -> None:
911911
f"ws://{config.ws_client_config.host}:{config.ws_client_config.port}"
912912
)
913913
self._client: Client = Client(
914-
self._ws_server_url, config.ws_client_config.aiohttp_session
914+
self._ws_server_url, aiohttp_session=config.ws_client_config.aiohttp_session
915915
)
916916
self._devices: dict[EUI64, WebSocketClientDevice] = {}
917917
self._groups: dict[int, WebSocketClientGroup] = {}

zha/websocket/__init__.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,9 @@
11
"""Websocket module for Zigbee Home Automation."""
2+
3+
from __future__ import annotations
4+
5+
from zha.exceptions import ZHAException
6+
7+
8+
class ZHAWebSocketException(ZHAException):
9+
"""Exception raised by websocket errors."""

zha/websocket/client/client.py

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
from async_timeout import timeout
1515

1616
from zha.event import EventBase
17-
from zha.exceptions import ZHAException
17+
from zha.websocket import ZHAWebSocketException
1818
from zha.websocket.client.model.messages import Message
1919
from zha.websocket.server.api.model import WebSocketCommand, WebSocketCommandResponse
2020

@@ -28,8 +28,8 @@ class Client(EventBase):
2828
def __init__(
2929
self,
3030
ws_server_url: str,
31-
aiohttp_session: ClientSession | None = None,
3231
*args: Any,
32+
aiohttp_session: ClientSession | None = None,
3333
**kwargs: Any,
3434
) -> None:
3535
"""Initialize the Client class."""
@@ -120,7 +120,7 @@ async def connect(self) -> None:
120120
)
121121
except client_exceptions.ClientError as err:
122122
_LOGGER.exception("Error connecting to server", exc_info=err)
123-
raise err
123+
raise ZHAWebSocketException from err
124124

125125
async def listen_loop(self) -> None:
126126
"""Listen to the websocket."""
@@ -132,7 +132,7 @@ async def listen_loop(self) -> None:
132132
async def listen(self) -> None:
133133
"""Start listening to the websocket."""
134134
if not self.connected:
135-
raise Exception("Not connected when start listening") # noqa: TRY002
135+
raise ZHAWebSocketException("Not connected when start listening")
136136

137137
assert self._client
138138

@@ -170,21 +170,21 @@ async def _receive_json_or_raise(self) -> dict:
170170
msg = await self._client.receive()
171171

172172
if msg.type in (WSMsgType.CLOSE, WSMsgType.CLOSED, WSMsgType.CLOSING):
173-
raise Exception("Connection was closed.") # noqa: TRY002
173+
raise ZHAWebSocketException(f"Connection was closed: {msg}")
174174

175175
if msg.type == WSMsgType.ERROR:
176-
raise Exception() # noqa: TRY002
176+
raise ZHAWebSocketException(f"WS message type was ERROR: {msg}")
177177

178178
if msg.type != WSMsgType.TEXT:
179-
raise Exception(f"Received non-Text message: {msg.type}") # noqa: TRY002
179+
raise ZHAWebSocketException(f"Received non-Text message: {msg}")
180180

181181
try:
182182
if len(msg.data) > SIZE_PARSE_JSON_EXECUTOR:
183183
data: dict = await self._loop.run_in_executor(None, msg.json)
184184
else:
185185
data = msg.json()
186186
except ValueError as err:
187-
raise Exception("Received invalid JSON.") from err # noqa: TRY002
187+
raise ZHAWebSocketException(f"Received invalid JSON: {msg}") from err
188188

189189
if _LOGGER.isEnabledFor(logging.DEBUG):
190190
_LOGGER.debug("Received message:\n%s\n", pprint.pformat(msg))
@@ -199,12 +199,12 @@ def _handle_incoming_message(self, msg: dict) -> None:
199199

200200
try:
201201
message = Message.model_validate(msg).root
202-
except Exception as err:
202+
except Exception as err: # pylint: disable=broad-except
203203
_LOGGER.exception("Error parsing message: %s", msg, exc_info=err)
204204
if msg["message_type"] == "result":
205205
future = self._result_futures.get(msg["message_id"])
206206
if future is not None:
207-
future.set_exception(err)
207+
future.set_exception(ZHAWebSocketException(err))
208208
return
209209
return
210210

@@ -220,9 +220,9 @@ def _handle_incoming_message(self, msg: dict) -> None:
220220
return
221221

222222
if msg["error_code"] != "zigbee_error":
223-
error = ZHAException(msg["message_id"], msg["error_code"])
223+
error = ZHAWebSocketException(msg["message_id"], msg["error_code"])
224224
else:
225-
error = ZHAException(
225+
error = ZHAWebSocketException(
226226
msg["message_id"],
227227
msg["zigbee_error_code"],
228228
msg["zigbee_error_message"],
@@ -242,16 +242,17 @@ def _handle_incoming_message(self, msg: dict) -> None:
242242

243243
try:
244244
self.emit(message.event_type, message)
245-
except Exception as err:
245+
except Exception as err: # pylint: disable=broad-except
246246
_LOGGER.exception("Error handling event", exc_info=err)
247+
raise ZHAWebSocketException from err
247248

248249
async def _send_json_message(self, message: str) -> None:
249250
"""Send a message.
250251
251252
Raises NotConnected if client not connected.
252253
"""
253254
if not self.connected:
254-
raise Exception() # noqa: TRY002
255+
raise ZHAWebSocketException("Sending message failed: no active connection.")
255256

256257
_LOGGER.debug("Publishing message:\n%s\n", pprint.pformat(message))
257258

0 commit comments

Comments
 (0)