1+ from __future__ import annotations
2+
13import asyncio
24import binascii
35import logging
46import struct
5- from typing import Any , Dict
7+ from typing import Any
68
79import zigpy .config
810import zigpy .serial
1214LOGGER = logging .getLogger (__name__ )
1315
1416
15- class Gateway (asyncio . Protocol ):
17+ class Gateway (zigpy . serial . SerialProtocol ):
1618 START = b"\x01 "
1719 END = b"\x03 "
1820
19- def __init__ (self , api , connected_future = None ):
20- self ._buffer = b""
21- self ._connected_future = connected_future
21+ def __init__ (self , api ):
22+ super ().__init__ ()
2223 self ._api = api
2324
24- def connection_lost (self , exc ) -> None :
25- """Port was closed expecteddly or unexpectedly."""
26- if self ._connected_future and not self ._connected_future .done ():
27- if exc is None :
28- self ._connected_future .set_result (True )
29- else :
30- self ._connected_future .set_exception (exc )
31- if exc is None :
32- LOGGER .debug ("Closed serial connection" )
33- return
34-
35- LOGGER .error ("Lost serial connection: %s" , exc )
36- self ._api .connection_lost (exc )
25+ def connection_lost (self , exc : Exception | None ) -> None :
26+ """Port was closed expectedly or unexpectedly."""
27+ super ().connection_lost (exc )
3728
38- def connection_made (self , transport ):
39- """Callback when the uart is connected"""
40- LOGGER .debug ("Connection made" )
41- self ._transport = transport
42- if self ._connected_future :
43- self ._connected_future .set_result (True )
29+ if self ._api is not None :
30+ self ._api .connection_lost (exc )
4431
4532 def close (self ):
46- if self . _transport :
47- self ._transport . close ()
33+ super (). close ()
34+ self ._api = None
4835
4936 def send (self , cmd , data = b"" ):
5037 """Send data, taking care of escaping and framing"""
@@ -60,8 +47,7 @@ def send(self, cmd, data=b""):
6047
6148 def data_received (self , data ):
6249 """Callback when there is data received from the uart"""
63- self ._buffer += data
64- # LOGGER.debug('data_received %s', self._buffer)
50+ super ().data_received (data )
6551 endpos = self ._buffer .find (self .END )
6652 while endpos != - 1 :
6753 startpos = self ._buffer .rfind (self .START , 0 , endpos )
@@ -71,7 +57,7 @@ def data_received(self, data):
7157 cmd , length , checksum , f_data , lqi = struct .unpack (
7258 "!HHB%dsB" % (len (frame ) - 6 ), frame
7359 )
74- if self . _length (frame ) != length :
60+ if len (frame ) - 5 != length :
7561 LOGGER .warning (
7662 "Invalid length: %s, data: %s" , length , len (frame ) - 6
7763 )
@@ -126,42 +112,28 @@ def _checksum(self, *args):
126112 chcksum ^= x
127113 return chcksum
128114
129- def _length (self , frame ):
130- length = len (frame ) - 5
131- return length
132-
133-
134- async def connect (device_config : Dict [str , Any ], api , loop = None ):
135- if loop is None :
136- loop = asyncio .get_event_loop ()
137-
138- connected_future = asyncio .Future ()
139- protocol = Gateway (api , connected_future )
140115
116+ async def connect (device_config : dict [str , Any ], api , loop = None ):
117+ loop = asyncio .get_running_loop ()
141118 port = device_config [zigpy .config .CONF_DEVICE_PATH ]
142- if port == "auto" :
143- port = await loop .run_in_executor (None , c .discover_port )
144119
145120 if await c .async_is_pizigate (port ):
146121 LOGGER .debug ("PiZiGate detected" )
147122 await c .async_set_pizigate_running_mode ()
148- # in case of pizigate:/dev/ttyAMA0 syntax
149- if port .startswith ("pizigate:" ):
150- port = port .replace ("pizigate:" , "" , 1 )
123+ port = port .replace ("pizigate:" , "" , 1 )
151124 elif await c .async_is_zigate_din (port ):
152125 LOGGER .debug ("ZiGate USB DIN detected" )
153126 await c .async_set_zigatedin_running_mode ()
154- elif c .is_zigate_wifi (port ):
155- LOGGER .debug ("ZiGate WiFi detected" )
156127
128+ protocol = Gateway (api )
157129 _ , protocol = await zigpy .serial .create_serial_connection (
158130 loop ,
159131 lambda : protocol ,
160132 url = port ,
161133 baudrate = device_config [zigpy .config .CONF_DEVICE_BAUDRATE ],
162- xonxoff = False ,
134+ flow_control = device_config [ zigpy . config . CONF_DEVICE_FLOW_CONTROL ] ,
163135 )
164136
165- await connected_future
137+ await protocol . wait_until_connected ()
166138
167139 return protocol
0 commit comments