pyowershades 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 vemboy20
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,19 @@
1
+ Metadata-Version: 2.4
2
+ Name: pyowershades
3
+ Version: 0.1.0
4
+ Summary: Asyncio library for PowerShades motorized blinds
5
+ Project-URL: Homepage, https://github.com/vemboy200/Pyowershades
6
+ Author-email: Vem Boynerian <vemboy20@gmail.com>
7
+ License: MIT
8
+ License-File: LICENSE
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Requires-Python: >=3.12
16
+ Description-Content-Type: text/markdown
17
+
18
+ # Pyowershades
19
+ A phython library for controlling powershades
@@ -0,0 +1,2 @@
1
+ # Pyowershades
2
+ A phython library for controlling powershades
@@ -0,0 +1,83 @@
1
+ """Asyncio library for PowerShades motorized blinds."""
2
+
3
+ from .connection import (
4
+ DiscoveredDevice,
5
+ PowerShadesConnection,
6
+ PowerShadesDeviceInfo,
7
+ PowerShadesTimeoutError,
8
+ async_discover_devices,
9
+ async_get_device_info,
10
+ )
11
+ from .const import (
12
+ DISCOVERY_TIMEOUT,
13
+ LIMIT_LOWER,
14
+ LIMIT_UPPER,
15
+ MODEL_NAMES,
16
+ OP_CLEAR_LIMITS,
17
+ OP_GET_DEVICE_NAME,
18
+ OP_GET_SERIAL,
19
+ OP_GET_SHADE_NAME,
20
+ OP_GET_STATUS,
21
+ OP_INDICATE,
22
+ OP_JOG_DOWN,
23
+ OP_JOG_STOP,
24
+ OP_JOG_UP,
25
+ OP_SET_LIMIT,
26
+ OP_SET_POSITION,
27
+ OP_STEP_DOWN,
28
+ OP_STEP_UP,
29
+ REQUEST_RETRIES,
30
+ REQUEST_TIMEOUT,
31
+ UDP_PORT,
32
+ )
33
+ from .protocol import (
34
+ GET_SHADE_NAME_PAYLOAD,
35
+ StatusReply,
36
+ build_packet,
37
+ build_set_limit_payload,
38
+ build_set_name_payload,
39
+ build_set_position_payload,
40
+ parse_device_name_reply,
41
+ parse_serial_reply,
42
+ parse_shade_name_reply,
43
+ parse_status_reply,
44
+ )
45
+
46
+ __all__ = [
47
+ "DiscoveredDevice",
48
+ "DISCOVERY_TIMEOUT",
49
+ "GET_SHADE_NAME_PAYLOAD",
50
+ "LIMIT_LOWER",
51
+ "LIMIT_UPPER",
52
+ "MODEL_NAMES",
53
+ "OP_CLEAR_LIMITS",
54
+ "OP_GET_DEVICE_NAME",
55
+ "OP_GET_SERIAL",
56
+ "OP_GET_SHADE_NAME",
57
+ "OP_GET_STATUS",
58
+ "OP_INDICATE",
59
+ "OP_JOG_DOWN",
60
+ "OP_JOG_STOP",
61
+ "OP_JOG_UP",
62
+ "OP_SET_LIMIT",
63
+ "OP_SET_POSITION",
64
+ "OP_STEP_DOWN",
65
+ "OP_STEP_UP",
66
+ "PowerShadesConnection",
67
+ "PowerShadesDeviceInfo",
68
+ "PowerShadesTimeoutError",
69
+ "REQUEST_RETRIES",
70
+ "REQUEST_TIMEOUT",
71
+ "StatusReply",
72
+ "UDP_PORT",
73
+ "async_discover_devices",
74
+ "async_get_device_info",
75
+ "build_packet",
76
+ "build_set_limit_payload",
77
+ "build_set_name_payload",
78
+ "build_set_position_payload",
79
+ "parse_device_name_reply",
80
+ "parse_serial_reply",
81
+ "parse_shade_name_reply",
82
+ "parse_status_reply",
83
+ ]
@@ -0,0 +1,268 @@
1
+ """Asyncio UDP transport and discovery for PowerShades devices."""
2
+
3
+ import asyncio
4
+ from collections.abc import Callable
5
+ import logging
6
+ from typing import TypedDict
7
+
8
+ from .const import (
9
+ BROADCAST_IP,
10
+ DISCOVERY_TIMEOUT,
11
+ OP_GET_DEVICE_NAME,
12
+ OP_GET_SERIAL,
13
+ OP_GET_SHADE_NAME,
14
+ OP_GET_STATUS,
15
+ REQUEST_RETRIES,
16
+ REQUEST_TIMEOUT,
17
+ UDP_PORT,
18
+ )
19
+ from .protocol import (
20
+ GET_SHADE_NAME_PAYLOAD,
21
+ StatusReply,
22
+ build_packet,
23
+ parse_device_name_reply,
24
+ parse_header,
25
+ parse_serial_reply,
26
+ parse_shade_name_reply,
27
+ parse_status_reply,
28
+ verify_packet,
29
+ )
30
+
31
+ _LOGGER = logging.getLogger(__name__)
32
+
33
+
34
+ class DiscoveredDevice(TypedDict):
35
+ """A device found via UDP broadcast discovery."""
36
+
37
+ ip: str
38
+ serial: int
39
+ model: int
40
+
41
+
42
+ class PowerShadesDeviceInfo(TypedDict):
43
+ """Information probed from a device during config flow validation."""
44
+
45
+ serial: int
46
+ name: str | None
47
+ model: int
48
+
49
+
50
+ class PowerShadesTimeoutError(Exception):
51
+ """The device did not reply in time."""
52
+
53
+
54
+ class _PowerShadesProtocol(asyncio.DatagramProtocol):
55
+ """Datagram protocol routing replies to pending requests and status pushes."""
56
+
57
+ def __init__(self, on_status: Callable[[StatusReply], None]) -> None:
58
+ self._on_status = on_status
59
+ # Keyed by op alone: real shades do not reliably echo the
60
+ # request's sequence (Get Status always replies sequence 1,
61
+ # whatever was sent). Requests on a connection are serialized,
62
+ # so at most one request per op is pending at a time.
63
+ self.pending: dict[int, asyncio.Future[bytes]] = {}
64
+
65
+ def datagram_received(self, data: bytes, addr: tuple[str, int]) -> None:
66
+ if not verify_packet(data):
67
+ _LOGGER.debug("Dropping invalid packet from %s: %s", addr[0], data.hex())
68
+ return
69
+ header = parse_header(data)
70
+ if header is None:
71
+ return
72
+ _LOGGER.debug(
73
+ "Received op=0x%02X seq=%d from %s: %s",
74
+ header.op,
75
+ header.sequence,
76
+ addr[0],
77
+ data.hex(),
78
+ )
79
+ fut = self.pending.pop(header.op, None)
80
+ if fut is not None and not fut.done():
81
+ fut.set_result(data)
82
+ return
83
+ if header.op == OP_GET_STATUS:
84
+ status = parse_status_reply(data)
85
+ if status is not None:
86
+ self._on_status(status)
87
+
88
+ def error_received(self, exc: Exception) -> None:
89
+ _LOGGER.debug("UDP error received: %s", exc)
90
+
91
+
92
+ class PowerShadesConnection:
93
+ """A single UDP endpoint talking to one PowerShades device."""
94
+
95
+ def __init__(self, host: str) -> None:
96
+ self._host = host
97
+ self._transport: asyncio.DatagramTransport | None = None
98
+ self._protocol: _PowerShadesProtocol | None = None
99
+ self._lock = asyncio.Lock()
100
+ self._sequence = 0
101
+ self._status_callback: Callable[[StatusReply], None] | None = None
102
+
103
+ @property
104
+ def host(self) -> str:
105
+ return self._host
106
+
107
+ def set_status_callback(self, callback: Callable[[StatusReply], None]) -> None:
108
+ self._status_callback = callback
109
+
110
+ def _handle_status(self, status: StatusReply) -> None:
111
+ if self._status_callback is not None:
112
+ self._status_callback(status)
113
+
114
+ async def async_connect(self) -> None:
115
+ loop = asyncio.get_running_loop()
116
+ self._transport, self._protocol = await loop.create_datagram_endpoint(
117
+ lambda: _PowerShadesProtocol(self._handle_status),
118
+ local_addr=("0.0.0.0", 0),
119
+ )
120
+
121
+ def _send(self, op: int, sequence: int, payload: bytes = b"") -> None:
122
+ if self._transport is None:
123
+ raise PowerShadesTimeoutError("Connection is closed")
124
+ packet = build_packet(op, sequence, payload=payload)
125
+ self._transport.sendto(packet, (self._host, UDP_PORT))
126
+ _LOGGER.debug(
127
+ "Sent op=0x%02X seq=%d to %s:%d: %s",
128
+ op,
129
+ sequence,
130
+ self._host,
131
+ UDP_PORT,
132
+ packet.hex(),
133
+ )
134
+
135
+ def _next_sequence(self) -> int:
136
+ self._sequence = (self._sequence + 1) % 256
137
+ return self._sequence
138
+
139
+ async def async_request(
140
+ self,
141
+ op: int,
142
+ payload: bytes = b"",
143
+ timeout: float = REQUEST_TIMEOUT,
144
+ retries: int = REQUEST_RETRIES,
145
+ ) -> bytes:
146
+ if self._protocol is None or self._transport is None:
147
+ raise PowerShadesTimeoutError("Connection is closed")
148
+ async with self._lock:
149
+ # Each attempt sends a fresh sequence, but replies are matched
150
+ # by op only — the device does not echo the sequence on all ops.
151
+ for _attempt in range(retries + 1):
152
+ sequence = self._next_sequence()
153
+ fut: asyncio.Future[bytes] = asyncio.get_running_loop().create_future()
154
+ self._protocol.pending[op] = fut
155
+ self._send(op, sequence, payload)
156
+ try:
157
+ return await asyncio.wait_for(fut, timeout)
158
+ except TimeoutError:
159
+ pass
160
+ finally:
161
+ if self._protocol is not None:
162
+ self._protocol.pending.pop(op, None)
163
+ raise PowerShadesTimeoutError(
164
+ f"No reply to op 0x{op:02X} from {self._host}"
165
+ )
166
+
167
+ def close(self) -> None:
168
+ if self._transport is not None:
169
+ self._transport.close()
170
+ self._transport = None
171
+ self._protocol = None
172
+
173
+
174
+ class _DiscoveryProtocol(asyncio.DatagramProtocol):
175
+ """Collects Get Serial replies during broadcast discovery."""
176
+
177
+ def __init__(self, results: dict[str, DiscoveredDevice]) -> None:
178
+ self._results = results
179
+
180
+ def datagram_received(self, data: bytes, addr: tuple[str, int]) -> None:
181
+ if not verify_packet(data):
182
+ _LOGGER.debug("Dropping invalid discovery reply from %s", addr[0])
183
+ return
184
+ parsed = parse_serial_reply(data)
185
+ # Key by the packet source address — it is authoritative, the
186
+ # IP embedded in the reply payload is not.
187
+ if parsed is not None and addr[0] not in self._results:
188
+ self._results[addr[0]] = {
189
+ "ip": addr[0],
190
+ "serial": parsed["serial"],
191
+ "model": parsed["model"],
192
+ }
193
+ _LOGGER.debug("Discovered device %s (serial %s)", addr[0], parsed["serial"])
194
+
195
+ def error_received(self, exc: Exception) -> None:
196
+ _LOGGER.debug("Discovery UDP error: %s", exc)
197
+
198
+
199
+ async def async_discover_devices(
200
+ local_addresses: list[str],
201
+ timeout: float = DISCOVERY_TIMEOUT,
202
+ ) -> list[DiscoveredDevice]:
203
+ """Discover PowerShades devices via UDP broadcast on all provided local addresses."""
204
+ loop = asyncio.get_running_loop()
205
+ results: dict[str, DiscoveredDevice] = {}
206
+ transports: list[asyncio.DatagramTransport] = []
207
+ packet = build_packet(OP_GET_SERIAL, sequence=0x01)
208
+
209
+ for address in local_addresses:
210
+ try:
211
+ transport, _protocol = await loop.create_datagram_endpoint(
212
+ lambda: _DiscoveryProtocol(results),
213
+ local_addr=(address, 0),
214
+ allow_broadcast=True,
215
+ )
216
+ except OSError as err:
217
+ _LOGGER.debug("Could not bind discovery socket to %s: %s", address, err)
218
+ continue
219
+ transport.sendto(packet, (BROADCAST_IP, UDP_PORT))
220
+ transports.append(transport)
221
+
222
+ if not transports:
223
+ return []
224
+
225
+ try:
226
+ await asyncio.sleep(timeout)
227
+ finally:
228
+ for transport in transports:
229
+ transport.close()
230
+
231
+ _LOGGER.info("Discovery complete, found %d device(s)", len(results))
232
+ return list(results.values())
233
+
234
+
235
+ async def async_get_device_info(ip_address: str) -> PowerShadesDeviceInfo:
236
+ """Probe a device for its serial number and name.
237
+
238
+ Raises PowerShadesTimeoutError if the device does not answer the
239
+ serial request.
240
+ """
241
+ connection = PowerShadesConnection(ip_address)
242
+ await connection.async_connect()
243
+ try:
244
+ reply = await connection.async_request(OP_GET_SERIAL, retries=1)
245
+ parsed = parse_serial_reply(reply)
246
+ if parsed is None:
247
+ raise PowerShadesTimeoutError(f"Malformed serial reply from {ip_address}")
248
+
249
+ name = None
250
+ for op, payload, parser in (
251
+ (OP_GET_SHADE_NAME, GET_SHADE_NAME_PAYLOAD, parse_shade_name_reply),
252
+ (OP_GET_DEVICE_NAME, b"", parse_device_name_reply),
253
+ ):
254
+ try:
255
+ name_reply = await connection.async_request(op, payload, retries=0)
256
+ except PowerShadesTimeoutError:
257
+ continue
258
+ name = parser(name_reply)
259
+ if name:
260
+ break
261
+
262
+ return {
263
+ "serial": parsed["serial"],
264
+ "name": name,
265
+ "model": parsed["model"],
266
+ }
267
+ finally:
268
+ connection.close()
@@ -0,0 +1,34 @@
1
+ """Constants for the PowerShades protocol."""
2
+
3
+ UDP_PORT = 42
4
+ BROADCAST_IP = "255.255.255.255"
5
+
6
+ # Protocol opcodes
7
+ OP_GET_SERIAL = 0x00
8
+ OP_SET_LIMIT = 0x01
9
+ OP_JOG_UP = 0x03
10
+ OP_JOG_DOWN = 0x04
11
+ OP_JOG_STOP = 0x05
12
+ OP_INDICATE = 0x08
13
+ OP_SET_POSITION = 0x1A
14
+ OP_GET_STATUS = 0x1D
15
+ OP_CLEAR_LIMITS = 0x1E
16
+ OP_STEP_UP = 0x23
17
+ OP_STEP_DOWN = 0x24
18
+ OP_GET_SHADE_NAME = 0x34
19
+ OP_GET_DEVICE_NAME = 0x3A
20
+
21
+ # Limit types
22
+ LIMIT_UPPER = 0x0000
23
+ LIMIT_LOWER = 0x0001
24
+
25
+ # Model byte in the Get Serial Number reply
26
+ MODEL_NAMES = {
27
+ 1: "PoE Shade",
28
+ 100: "RF Gateway",
29
+ }
30
+
31
+ # Timing
32
+ DISCOVERY_TIMEOUT = 3.0
33
+ REQUEST_TIMEOUT = 2.0
34
+ REQUEST_RETRIES = 2
@@ -0,0 +1,210 @@
1
+ """PowerShades UDP packet building and parsing.
2
+
3
+ Packet layout (little-endian):
4
+ Length(2) + CRC16-XMODEM(2) + Op(1) + Sequence(1) + Channel(1) + Reserved(1) + Payload
5
+ The CRC covers Op + Sequence + Channel + Reserved + Payload.
6
+ """
7
+
8
+ from dataclasses import dataclass
9
+ import struct
10
+ from typing import TypedDict
11
+
12
+ from .const import OP_GET_STATUS
13
+
14
+
15
+ class SerialReply(TypedDict):
16
+ """Parsed Get Serial Number reply."""
17
+
18
+ model: int
19
+ direction: int
20
+ serial: int
21
+ dhcp_enabled: bool
22
+
23
+
24
+ HEADER_SIZE = 8
25
+
26
+ CrcTable = [
27
+ 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7,
28
+ 0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF,
29
+ 0x1231, 0x0210, 0x3273, 0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6,
30
+ 0x9339, 0x8318, 0xB37B, 0xA35A, 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE,
31
+ 0x2462, 0x3443, 0x0420, 0x1401, 0x64E6, 0x74C7, 0x44A4, 0x5485,
32
+ 0xA56A, 0xB54B, 0x8528, 0x9509, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D,
33
+ 0x3653, 0x2672, 0x1611, 0x0630, 0x76D7, 0x66F6, 0x5695, 0x46B4,
34
+ 0xB75B, 0xA77A, 0x9719, 0x8738, 0xF7DF, 0xE7FE, 0xD79D, 0xC7BC,
35
+ 0x48C4, 0x58E5, 0x6886, 0x78A7, 0x0840, 0x1861, 0x2802, 0x3823,
36
+ 0xC9CC, 0xD9ED, 0xE98E, 0xF9AF, 0x8948, 0x9969, 0xA90A, 0xB92B,
37
+ 0x5AF5, 0x4AD4, 0x7AB7, 0x6A96, 0x1A71, 0x0A50, 0x3A33, 0x2A12,
38
+ 0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E, 0x9B79, 0x8B58, 0xBB3B, 0xAB1A,
39
+ 0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x2C22, 0x3C03, 0x0C60, 0x1C41,
40
+ 0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD, 0xAD2A, 0xBD0B, 0x8D68, 0x9D49,
41
+ 0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70,
42
+ 0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78,
43
+ 0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F,
44
+ 0x1080, 0x00A1, 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067,
45
+ 0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C, 0xE37F, 0xF35E,
46
+ 0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256,
47
+ 0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0xF56E, 0xE54F, 0xD52C, 0xC50D,
48
+ 0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,
49
+ 0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C,
50
+ 0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634,
51
+ 0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB,
52
+ 0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1, 0x3882, 0x28A3,
53
+ 0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A,
54
+ 0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92,
55
+ 0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9,
56
+ 0x7C26, 0x6C07, 0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1,
57
+ 0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8,
58
+ 0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0,
59
+ ]
60
+
61
+ # Get/Set flag payload for the Get PoE Shade Name command (0 = Get)
62
+ GET_SHADE_NAME_PAYLOAD = b"\x00"
63
+
64
+
65
+ def crc16_xmodem(data: bytes) -> int:
66
+ crc = 0
67
+ for b in data:
68
+ crc = ((crc << 8) & 0xFFFF) ^ CrcTable[((crc >> 8) ^ b) & 0xFF]
69
+ return crc
70
+
71
+
72
+ def build_packet(
73
+ op: int, sequence: int = 0, channel: int = 0, payload: bytes = b""
74
+ ) -> bytes:
75
+ reserved = 0
76
+ crc_data = struct.pack("<BBBB", op, sequence, channel, reserved) + payload
77
+ crc = crc16_xmodem(crc_data)
78
+ return (
79
+ struct.pack("<HHBBBB", len(payload), crc, op, sequence, channel, reserved)
80
+ + payload
81
+ )
82
+
83
+
84
+ def build_set_position_payload(percent: int) -> bytes:
85
+ mask = 0x0001 # MASK_PERCENT
86
+ tilt = 0
87
+ channel_mask = 0
88
+ return struct.pack("<HhhI", mask, percent, tilt, channel_mask)
89
+
90
+
91
+ def build_set_limit_payload(limit_type: int) -> bytes:
92
+ return struct.pack("<H", limit_type)
93
+
94
+
95
+ def build_set_name_payload(name: str) -> bytes:
96
+ return b"\x01" + name.encode("ascii")[:50].ljust(50, b"\x00")
97
+
98
+
99
+ @dataclass(frozen=True)
100
+ class PacketHeader:
101
+ """Parsed packet header."""
102
+
103
+ length: int
104
+ crc: int
105
+ op: int
106
+ sequence: int
107
+ channel: int
108
+
109
+
110
+ def parse_header(data: bytes) -> PacketHeader | None:
111
+ if len(data) < HEADER_SIZE:
112
+ return None
113
+ length, crc, op, sequence, channel, _reserved = struct.unpack(
114
+ "<HHBBBB", data[:HEADER_SIZE]
115
+ )
116
+ return PacketHeader(length, crc, op, sequence, channel)
117
+
118
+
119
+ def verify_packet(data: bytes) -> bool:
120
+ """Validate a packet's length field and CRC.
121
+
122
+ The CRC covers Op + Sequence + Channel + Reserved + Payload for
123
+ replies as well as commands (verified against real device replies).
124
+ """
125
+ header = parse_header(data)
126
+ if header is None or len(data) < HEADER_SIZE + header.length:
127
+ return False
128
+ return crc16_xmodem(data[4 : HEADER_SIZE + header.length]) == header.crc
129
+
130
+
131
+ def parse_serial_reply(data: bytes) -> SerialReply | None:
132
+ """Parse a Get Serial Number reply packet.
133
+
134
+ Payload layout (after the 8-byte header): Model(1) Pad1(1) Pad2(1)
135
+ Direction(1) SerialLow(4) SerialHigh(4) DhcpEnabled(1) IP(4)
136
+ Subnet(4) Gateway(4) Internal(50).
137
+ """
138
+ if len(data) < 24:
139
+ return None
140
+ model = data[8]
141
+ direction = data[11]
142
+ serial_low = struct.unpack("<I", data[12:16])[0]
143
+ serial_high = struct.unpack("<I", data[16:20])[0]
144
+ dhcp_enabled = bool(data[20])
145
+ return {
146
+ "model": model,
147
+ "direction": direction,
148
+ "serial": (serial_high << 32) | serial_low,
149
+ "dhcp_enabled": dhcp_enabled,
150
+ }
151
+
152
+
153
+ def _decode_name(name_bytes: bytes) -> str | None:
154
+ name = name_bytes.split(b"\x00")[0].decode("ascii", errors="ignore").strip()
155
+ return name or None
156
+
157
+
158
+ def parse_device_name_reply(data: bytes) -> str | None:
159
+ if len(data) < 58: # 8-byte header + 50-byte name
160
+ return None
161
+ return _decode_name(data[8:58])
162
+
163
+
164
+ def parse_shade_name_reply(data: bytes) -> str | None:
165
+ if len(data) < 59: # 8-byte header + 1-byte get/set flag + 50-byte name
166
+ return None
167
+ return _decode_name(data[9:59])
168
+
169
+
170
+ @dataclass(frozen=True)
171
+ class StatusReply:
172
+ """Parsed status reply."""
173
+
174
+ position: int | None
175
+ battery_mv: int
176
+
177
+
178
+ def parse_status_reply(data: bytes) -> StatusReply | None:
179
+ header = parse_header(data)
180
+ if header is None or header.op != OP_GET_STATUS:
181
+ return None
182
+ payload = data[HEADER_SIZE : HEADER_SIZE + header.length]
183
+ if len(payload) < 30:
184
+ return None
185
+ (
186
+ percent,
187
+ _tilt,
188
+ _memory,
189
+ battery_mv,
190
+ _time,
191
+ _cycles,
192
+ _stalls,
193
+ _temperature,
194
+ _raw_percent,
195
+ _raw_tilt,
196
+ ) = struct.unpack("<hhHHIIIhII", payload[:30])
197
+ position = percent if 0 <= percent <= 100 else None
198
+ return StatusReply(position=position, battery_mv=battery_mv)
199
+
200
+
201
+ def battery_percentage(battery_mv: int | None) -> int | None:
202
+ """Convert battery voltage (mV) to a rough percentage (3.0V=0%, 4.2V=100%)."""
203
+ if battery_mv is None:
204
+ return None
205
+ voltage = battery_mv / 1000.0
206
+ if voltage <= 3.0:
207
+ return 0
208
+ if voltage >= 4.2:
209
+ return 100
210
+ return int((voltage - 3.0) / (4.2 - 3.0) * 100)
File without changes
@@ -0,0 +1,26 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "pyowershades"
7
+ version = "0.1.0"
8
+ description = "Asyncio library for PowerShades motorized blinds"
9
+ readme = "README.md"
10
+ license = {text = "MIT"}
11
+ requires-python = ">=3.12"
12
+ authors = [
13
+ {name = "Vem Boynerian", email = "vemboy20@gmail.com"},
14
+ ]
15
+ classifiers = [
16
+ "Development Status :: 3 - Alpha",
17
+ "Intended Audience :: Developers",
18
+ "License :: OSI Approved :: MIT License",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3.12",
21
+ "Programming Language :: Python :: 3.13",
22
+ ]
23
+ dependencies = []
24
+
25
+ [project.urls]
26
+ Homepage = "https://github.com/vemboy200/Pyowershades"