3
3
4
4
import asyncio
5
5
import logging
6
- from types import TracebackType
7
- from typing import TYPE_CHECKING , Any , Callable , Dict , Final , Optional , cast
8
6
import uuid
7
+ from collections .abc import Callable
8
+ from types import TracebackType
9
+ from typing import TYPE_CHECKING , Any , Final , cast
9
10
10
11
from aiohttp import ClientSession
11
12
12
13
from matter_server .common .errors import ERROR_MAP
13
-
14
- from ..common .helpers .util import dataclass_from_dict , dataclass_to_dict
15
- from ..common .models import (
14
+ from matter_server .common .helpers .util import dataclass_from_dict , dataclass_to_dict
15
+ from matter_server .common .models import (
16
16
APICommand ,
17
17
CommandMessage ,
18
18
ErrorResultMessage ,
25
25
ServerInfoMessage ,
26
26
SuccessResultMessage ,
27
27
)
28
+
28
29
from .connection import MatterClientConnection
29
30
from .exceptions import ConnectionClosed , InvalidServerVersion , InvalidState
30
31
from .models .node import MatterNode
@@ -42,8 +43,8 @@ def __init__(self, ws_server_url: str, aiohttp_session: ClientSession):
42
43
"""Initialize the Client class."""
43
44
self .connection = MatterClientConnection (ws_server_url , aiohttp_session )
44
45
self .logger = logging .getLogger (__package__ )
45
- self ._nodes : Dict [int , MatterNode ] = {}
46
- self ._result_futures : Dict [str , asyncio .Future ] = {}
46
+ self ._nodes : dict [int , MatterNode ] = {}
47
+ self ._result_futures : dict [str , asyncio .Future ] = {}
47
48
self ._subscribers : dict [str , list [Callable [[EventType , Any ], None ]]] = {}
48
49
self ._stop_called : bool = False
49
50
self ._loop : asyncio .AbstractEventLoop | None = None
@@ -56,9 +57,9 @@ def server_info(self) -> ServerInfoMessage | None:
56
57
def subscribe (
57
58
self ,
58
59
callback : Callable [[EventType , Any ], None ],
59
- event_filter : Optional [ EventType ] = None ,
60
- node_filter : Optional [ int ] = None ,
61
- attr_path_filter : Optional [ str ] = None ,
60
+ event_filter : EventType | None = None ,
61
+ node_filter : int | None = None ,
62
+ attr_path_filter : str | None = None ,
62
63
) -> Callable [[], None ]:
63
64
"""
64
65
Subscribe to node and server events.
@@ -70,16 +71,10 @@ def subscribe(
70
71
# for fast lookups we create a key based on the filters, allowing
71
72
# a "catch all" with a wildcard (*).
72
73
_event_filter : str
73
- if event_filter is None :
74
- _event_filter = SUB_WILDCARD
75
- else :
76
- _event_filter = event_filter .value
74
+ _event_filter = SUB_WILDCARD if event_filter is None else event_filter .value
77
75
78
76
_node_filter : str
79
- if node_filter is None :
80
- _node_filter = SUB_WILDCARD
81
- else :
82
- _node_filter = str (node_filter )
77
+ _node_filter = SUB_WILDCARD if node_filter is None else str (node_filter )
83
78
84
79
if attr_path_filter is None :
85
80
attr_path_filter = SUB_WILDCARD
@@ -123,9 +118,7 @@ async def commission_on_network(self, setup_pin_code: int) -> MatterNodeData:
123
118
124
119
async def set_wifi_credentials (self , ssid : str , credentials : str ) -> None :
125
120
"""Set WiFi credentials for commissioning to a (new) device."""
126
- await self .send_command (
127
- APICommand .SET_WIFI_CREDENTIALS , ssid = ssid , credentials = credentials
128
- )
121
+ await self .send_command (APICommand .SET_WIFI_CREDENTIALS , ssid = ssid , credentials = credentials )
129
122
130
123
async def set_thread_operational_dataset (self , dataset : str ) -> None :
131
124
"""Set Thread Operational dataset in the stack."""
@@ -137,7 +130,7 @@ async def open_commissioning_window(
137
130
timeout : int = 300 ,
138
131
iteration : int = 1000 ,
139
132
option : int = 0 ,
140
- discriminator : Optional [ int ] = None ,
133
+ discriminator : int | None = None ,
141
134
) -> int :
142
135
"""
143
136
Open a commissioning window to commission a device present on this controller to another.
@@ -230,10 +223,7 @@ async def send_command_no_wait(
230
223
if not self .server_info :
231
224
raise InvalidState ("Not connected" )
232
225
233
- if (
234
- require_schema is not None
235
- and require_schema > self .server_info .schema_version
236
- ):
226
+ if require_schema is not None and require_schema > self .server_info .schema_version :
237
227
raise InvalidServerVersion (
238
228
"Command not available due to incompatible server version. Update the Matter "
239
229
f"Server to a version that supports at least api schema { require_schema } ."
@@ -268,15 +258,10 @@ async def start_listening(self, init_ready: asyncio.Event | None = None) -> None
268
258
message_id = uuid .uuid4 ().hex , command = APICommand .START_LISTENING
269
259
)
270
260
await self .connection .send_message (message )
271
- nodes_msg = cast (
272
- SuccessResultMessage , await self .connection .receive_message_or_raise ()
273
- )
261
+ nodes_msg = cast (SuccessResultMessage , await self .connection .receive_message_or_raise ())
274
262
# a full dump of all nodes will be the result of the start_listening command
275
263
# create MatterNode objects from the basic MatterNodeData objects
276
- nodes = [
277
- MatterNode (dataclass_from_dict (MatterNodeData , x ))
278
- for x in nodes_msg .result
279
- ]
264
+ nodes = [MatterNode (dataclass_from_dict (MatterNodeData , x )) for x in nodes_msg .result ]
280
265
self ._nodes = {node .node_id : node for node in nodes }
281
266
# once we've hit this point we're all set
282
267
self .logger .info ("Matter client initialized." )
@@ -373,8 +358,8 @@ def _signal_event(
373
358
self ,
374
359
event : EventType ,
375
360
data : Any = None ,
376
- node_id : Optional [ int ] = None ,
377
- attribute_path : Optional [ str ] = None ,
361
+ node_id : int | None = None ,
362
+ attribute_path : str | None = None ,
378
363
) -> None :
379
364
"""Signal event to all subscribers."""
380
365
# instead of iterating all subscribers we iterate over subscription keys
@@ -390,7 +375,7 @@ def _signal_event(
390
375
for callback in self ._subscribers .get (key , []):
391
376
callback (event , data )
392
377
393
- async def __aenter__ (self ) -> " MatterClient" :
378
+ async def __aenter__ (self ) -> MatterClient :
394
379
"""Initialize and connect the Matter Websocket client."""
395
380
await self .connect ()
396
381
return self
0 commit comments