Debian Codegraph @

examples/mockdevice.py

raw symbols SCIP
1 import asyncio
2 import logging
3 import socket
4 from typing import Optional
5
6 from flux_led.aioscanner import AIOBulbScanner
7 from flux_led.protocol import OUTER_MESSAGE_WRAPPER
8
9 logging.basicConfig(level=logging.DEBUG)
10
11 _LOGGER = logging.getLogger(__name__)
12
13 DEVICE_ID = 0xA1
14 VERSION = 9
15 MINOR_VERSION = 28
16 ON_AT_START = False
17 # MODEL = "AK001-ZJ2101" # Supports auto on
18 # MODEL = "AK001-ZJ2145" # Supports dimmable effects
19 MODEL = "AK001-ZJ2147"
20
21
22 def get_local_ip():
23 """Find the local ip address."""
24 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
25 s.setblocking(False)
26 try:
27 s.connect(("10.255.255.255", 1))
28 return s.getsockname()[0]
29 except Exception:
30 return None
31 finally:
32 s.close()
33
34
35 class MagicHomeDiscoveryProtocol(asyncio.Protocol):
36 """A asyncio.Protocol implementing the MagicHome discovery protocol."""
37
38 def __init__(self) -> None:
39 self.loop = asyncio.get_running_loop()
40 self.local_ip = get_local_ip()
41 self.transport: Optional[asyncio.BaseTransport] = None
42
43 def connection_made(self, transport):
44 self.transport = transport
45
46 def send(self, data: bytes, addr: tuple[str, int]) -> None:
47 """Trigger on data."""
48 _LOGGER.debug(
49 "UDP %s => %s (%d)",
50 addr,
51 data,
52 len(data),
53 )
54 self.transport.sendto(data, addr)
55
56 def datagram_received(self, data: bytes, addr: tuple[str, int]) -> None:
57 """Trigger on data."""
58 _LOGGER.debug(
59 "UDP %s <= %s (%d)",
60 addr,
61 data,
62 len(data),
63 )
64 assert self.transport is not None
65 model_str = hex(DEVICE_ID)[2:].zfill(2).upper()
66 version_str = hex(VERSION)[2:].zfill(2).upper()
67 minor_version_str = str(MINOR_VERSION).zfill(2).upper()
68 if data.startswith(AIOBulbScanner.DISCOVER_MESSAGE):
69 self.send(
70 f"{self.local_ip},B4E842{model_str}{version_str}{minor_version_str},{MODEL}".encode(),
71 addr,
72 )
73 if data.startswith(AIOBulbScanner.VERSION_MESSAGE):
74 model_str = hex(DEVICE_ID)[2:].zfill(2).upper()
75 self.send(
76 f"+ok={model_str}_{minor_version_str}_20210428_ZG-BL\r".encode(), addr
77 )
78
79 def error_received(self, ex: Optional[Exception]) -> None:
80 """Handle error."""
81 _LOGGER.debug("LEDENETDiscovery error: %s", ex)
82
83 def connection_lost(self, ex: Optional[Exception]) -> None:
84 """The connection is lost."""
85
86
87 class MagichomeServerProtocol(asyncio.Protocol):
88 """A asyncio.Protocol implementing the MagicHome protocol."""
89
90 def __init__(self) -> None:
91 self.loop = asyncio.get_running_loop()
92 self.handler = None
93 self.peername = None
94 self.transport: Optional[asyncio.BaseTransport] = None
95
96 def connection_lost(self, exc: Exception) -> None:
97 """Handle connection lost."""
98 _LOGGER.debug("%s: Connection lost: %s", self.peername, exc)
99
100 def connection_made(self, transport: asyncio.Transport) -> None:
101 """Handle incoming connection."""
102 _LOGGER.debug("%s: Connection made", transport)
103 self.peername = transport.get_extra_info("peername")
104 self.transport = transport
105
106 def send(self, data: bytes, random_byte: Optional[None]) -> None:
107 """Trigger on data."""
108 if random_byte is not None:
109 msg = self.construct_wrapped_message(data, random_byte)
110 else:
111 msg = data
112 _LOGGER.debug(
113 "TCP %s => %s (%d)",
114 self.peername,
115 " ".join(f"0x{x:02X}" for x in msg),
116 len(msg),
117 )
118 self.transport.write(msg)
119
120 def data_received(self, data: bytes) -> None:
121 """Process new data from the socket."""
122 _LOGGER.debug(
123 "TCP %s <= %s (%d)",
124 self.peername,
125 " ".join(f"0x{x:02X}" for x in data),
126 len(data),
127 )
128 assert self.transport is not None
129 if data.startswith(bytearray([*OUTER_MESSAGE_WRAPPER])):
130 msg = data[10:-1]
131 random = data[7]
132 else:
133 random = None
134 msg = data
135
136 if msg.startswith(bytearray([0x81])):
137 self.send(
138 self.construct_message(
139 bytearray(
140 [
141 0x81,
142 DEVICE_ID,
143 0x23 if ON_AT_START else 0x24,
144 0x61,
145 0xC5,
146 0x17,
147 0x18,
148 0x00,
149 0x00,
150 0x00,
151 VERSION,
152 0xF0,
153 0xF2,
154 ]
155 )
156 ),
157 random,
158 )
159
160 def construct_wrapped_message(
161 self, inner_msg: bytearray, random_byte: int
162 ) -> bytearray:
163 """Construct a wrapped message."""
164 inner_msg_len = len(inner_msg)
165 return self.construct_message(
166 bytearray(
167 [
168 *OUTER_MESSAGE_WRAPPER,
169 random_byte,
170 inner_msg_len >> 8,
171 inner_msg_len & 0xFF,
172 *inner_msg,
173 ]
174 )
175 )
176
177 def construct_message(self, raw_bytes: bytearray) -> bytearray:
178 """Calculate checksum of byte array and add to end."""
179 csum = sum(raw_bytes) & 0xFF
180 raw_bytes.append(csum)
181 return raw_bytes
182
183
184 async def go():
185 loop = asyncio.get_running_loop()
186 await loop.create_server(
187 lambda: MagichomeServerProtocol(),
188 host="0.0.0.0",
189 port=5577,
190 )
191 await loop.create_datagram_endpoint(
192 lambda: MagicHomeDiscoveryProtocol(),
193 local_addr=("0.0.0.0", AIOBulbScanner.DISCOVERY_PORT),
194 )
195 await asyncio.sleep(86400)
196
197
198 asyncio.run(go())