recsrmesh 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,165 @@
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+
9
+ This version of the GNU Lesser General Public License incorporates
10
+ the terms and conditions of version 3 of the GNU General Public
11
+ License, supplemented by the additional permissions listed below.
12
+
13
+ 0. Additional Definitions.
14
+
15
+ As used herein, "this License" refers to version 3 of the GNU Lesser
16
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
+ General Public License.
18
+
19
+ "The Library" refers to a covered work governed by this License,
20
+ other than an Application or a Combined Work as defined below.
21
+
22
+ An "Application" is any work that makes use of an interface provided
23
+ by the Library, but which is not otherwise based on the Library.
24
+ Defining a subclass of a class defined by the Library is deemed a mode
25
+ of using an interface provided by the Library.
26
+
27
+ A "Combined Work" is a work produced by combining or linking an
28
+ Application with the Library. The particular version of the Library
29
+ with which the Combined Work was made is also called the "Linked
30
+ Version".
31
+
32
+ The "Minimal Corresponding Source" for a Combined Work means the
33
+ Corresponding Source for the Combined Work, excluding any source code
34
+ for portions of the Combined Work that, considered in isolation, are
35
+ based on the Application, and not on the Linked Version.
36
+
37
+ The "Corresponding Application Code" for a Combined Work means the
38
+ object code and/or source code for the Application, including any data
39
+ and utility programs needed for reproducing the Combined Work from the
40
+ Application, but excluding the System Libraries of the Combined Work.
41
+
42
+ 1. Exception to Section 3 of the GNU GPL.
43
+
44
+ You may convey a covered work under sections 3 and 4 of this License
45
+ without being bound by section 3 of the GNU GPL.
46
+
47
+ 2. Conveying Modified Versions.
48
+
49
+ If you modify a copy of the Library, and, in your modifications, a
50
+ facility refers to a function or data to be supplied by an Application
51
+ that uses the facility (other than as an argument passed when the
52
+ facility is invoked), then you may convey a copy of the modified
53
+ version:
54
+
55
+ a) under this License, provided that you make a good faith effort to
56
+ ensure that, in the event an Application does not supply the
57
+ function or data, the facility still operates, and performs
58
+ whatever part of its purpose remains meaningful, or
59
+
60
+ b) under the GNU GPL, with none of the additional permissions of
61
+ this License applicable to that copy.
62
+
63
+ 3. Object Code Incorporating Material from Library Header Files.
64
+
65
+ The object code form of an Application may incorporate material from
66
+ a header file that is part of the Library. You may convey such object
67
+ code under terms of your choice, provided that, if the incorporated
68
+ material is not limited to numerical parameters, data structure
69
+ layouts and accessors, or small macros, inline functions and templates
70
+ (ten or fewer lines in length), you do both of the following:
71
+
72
+ a) Give prominent notice with each copy of the object code that the
73
+ Library is used in it and that the Library and its use are
74
+ covered by this License.
75
+
76
+ b) Accompany the object code with a copy of the GNU GPL and this license
77
+ document.
78
+
79
+ 4. Combined Works.
80
+
81
+ You may convey a Combined Work under terms of your choice that,
82
+ taken together, effectively do not restrict modification of the
83
+ portions of the Library contained in the Combined Work and reverse
84
+ engineering for debugging such modifications, if you also do each of
85
+ the following:
86
+
87
+ a) Give prominent notice with each copy of the Combined Work that
88
+ the Library is used in it and that the Library and its use are
89
+ covered by this License.
90
+
91
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
+ document.
93
+
94
+ c) For a Combined Work that displays copyright notices during
95
+ execution, include the copyright notice for the Library among
96
+ these notices, as well as a reference directing the user to the
97
+ copies of the GNU GPL and this license document.
98
+
99
+ d) Do one of the following:
100
+
101
+ 0) Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+
109
+ 1) Use a suitable shared library mechanism for linking with the
110
+ Library. A suitable mechanism is one that (a) uses at run time
111
+ a copy of the Library already present on the user's computer
112
+ system, and (b) will operate properly with a modified version
113
+ of the Library that is interface-compatible with the Linked
114
+ Version.
115
+
116
+ e) Provide Installation Information, but only if you would otherwise
117
+ be required to provide such information under section 6 of the
118
+ GNU GPL, and only to the extent that such information is
119
+ necessary to install and execute a modified version of the
120
+ Combined Work produced by recombining or relinking the
121
+ Application with a modified version of the Linked Version. (If
122
+ you use option 4d0, the Installation Information must accompany
123
+ the Minimal Corresponding Source and Corresponding Application
124
+ Code. If you use option 4d1, you must provide the Installation
125
+ Information in the manner specified by section 6 of the GNU GPL
126
+ for conveying Corresponding Source.)
127
+
128
+ 5. Combined Libraries.
129
+
130
+ You may place library facilities that are a work based on the
131
+ Library side by side in a single library together with other library
132
+ facilities that are not Applications and are not covered by this
133
+ License, and convey such a combined library under terms of your
134
+ choice, if you do both of the following:
135
+
136
+ a) Accompany the combined library with a copy of the same work based
137
+ on the Library, uncombined with any other library facilities,
138
+ conveyed under the terms of this License.
139
+
140
+ b) Give prominent notice with the combined library that part of it
141
+ is a work based on the Library, and explaining where to find the
142
+ accompanying uncombined form of the same work.
143
+
144
+ 6. Revised Versions of the GNU Lesser General Public License.
145
+
146
+ The Free Software Foundation may publish revised and/or new versions
147
+ of the GNU Lesser General Public License from time to time. Such new
148
+ versions will be similar in spirit to the present version, but may
149
+ differ in detail to address new problems or concerns.
150
+
151
+ Each version is given a distinguishing version number. If the
152
+ Library as you received it specifies that a certain numbered version
153
+ of the GNU Lesser General Public License "or any later version"
154
+ applies to it, you have the option of following the terms and
155
+ conditions either of that published version or of any later version
156
+ published by the Free Software Foundation. If the Library as you
157
+ received it does not specify a version number of the GNU Lesser
158
+ General Public License, you may choose any version of the GNU Lesser
159
+ General Public License ever published by the Free Software Foundation.
160
+
161
+ If the Library as you received it specifies that a proxy can decide
162
+ whether future versions of the GNU Lesser General Public License shall
163
+ apply, that proxy's public statement of acceptance of any version is
164
+ permanent authorization for you to choose that version for the
165
+ Library.
@@ -0,0 +1,36 @@
1
+ Metadata-Version: 2.4
2
+ Name: recsrmesh
3
+ Version: 0.1.0
4
+ Summary: CSRMesh protocol library
5
+ Author-email: Sean Kinsey <oyvind@kinsey.no>
6
+ License: LGPL-3.0-or-later
7
+ Project-URL: Homepage, https://github.com/oyvindkinsey/recsrmesh
8
+ Project-URL: Repository, https://github.com/oyvindkinsey/recsrmesh
9
+ Project-URL: Issues, https://github.com/oyvindkinsey/recsrmesh/issues
10
+ Keywords: csrmesh,bluetooth,mesh,ble
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Topic :: Home Automation
18
+ Classifier: Topic :: System :: Hardware
19
+ Requires-Python: >=3.11
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ Requires-Dist: bleak>=0.21.0
23
+ Requires-Dist: cryptography>=41.0.0
24
+ Requires-Dist: pycryptodomex>=3.23.0
25
+ Provides-Extra: dev
26
+ Requires-Dist: pytest>=7.4.0; extra == "dev"
27
+ Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
28
+ Requires-Dist: pytest-cov>=4.1.0; extra == "dev"
29
+ Requires-Dist: pytest-mock>=3.11.0; extra == "dev"
30
+ Requires-Dist: ruff>=0.1.0; extra == "dev"
31
+ Requires-Dist: mypy>=1.5.0; extra == "dev"
32
+ Provides-Extra: test
33
+ Requires-Dist: pytest>=7.4.0; extra == "test"
34
+ Requires-Dist: pytest-asyncio>=0.21.0; extra == "test"
35
+ Requires-Dist: pytest-cov>=4.1.0; extra == "test"
36
+ Dynamic: license-file
@@ -0,0 +1,90 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "recsrmesh"
7
+ version = "0.1.0"
8
+ description = "CSRMesh protocol library"
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = {text = "LGPL-3.0-or-later"}
12
+ authors = [
13
+ {name = "Sean Kinsey", email = "oyvind@kinsey.no"}
14
+ ]
15
+ keywords = [
16
+ "csrmesh",
17
+ "bluetooth",
18
+ "mesh",
19
+ "ble",
20
+ ]
21
+ classifiers = [
22
+ "Development Status :: 3 - Alpha",
23
+ "Intended Audience :: Developers",
24
+ "License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)",
25
+ "Programming Language :: Python :: 3",
26
+ "Programming Language :: Python :: 3.11",
27
+ "Programming Language :: Python :: 3.12",
28
+ "Topic :: Home Automation",
29
+ "Topic :: System :: Hardware",
30
+ ]
31
+
32
+ dependencies = [
33
+ "bleak>=0.21.0",
34
+ "cryptography>=41.0.0",
35
+ "pycryptodomex>=3.23.0",
36
+ ]
37
+
38
+ [project.optional-dependencies]
39
+ dev = [
40
+ "pytest>=7.4.0",
41
+ "pytest-asyncio>=0.21.0",
42
+ "pytest-cov>=4.1.0",
43
+ "pytest-mock>=3.11.0",
44
+ "ruff>=0.1.0",
45
+ "mypy>=1.5.0",
46
+ ]
47
+ test = [
48
+ "pytest>=7.4.0",
49
+ "pytest-asyncio>=0.21.0",
50
+ "pytest-cov>=4.1.0",
51
+ ]
52
+
53
+ [project.urls]
54
+ Homepage = "https://github.com/oyvindkinsey/recsrmesh"
55
+ Repository = "https://github.com/oyvindkinsey/recsrmesh"
56
+ Issues = "https://github.com/oyvindkinsey/recsrmesh/issues"
57
+
58
+ [tool.setuptools]
59
+ package-dir = {"" = "src"}
60
+
61
+ [tool.setuptools.packages.find]
62
+ where = ["src"]
63
+ include = ["recsrmesh*"]
64
+ exclude = ["tests*"]
65
+
66
+ [tool.pytest.ini_options]
67
+ minversion = "7.0"
68
+ testpaths = ["tests"]
69
+ python_files = ["test_*.py", "*_test.py"]
70
+ python_classes = ["Test*"]
71
+ python_functions = ["test_*"]
72
+ asyncio_mode = "auto"
73
+ addopts = [
74
+ "-ra",
75
+ "--strict-markers",
76
+ "--strict-config",
77
+ "--tb=short",
78
+ ]
79
+
80
+ [tool.ruff]
81
+ line-length = 100
82
+ target-version = "py311"
83
+
84
+ [tool.ruff.lint]
85
+ select = ["E", "W", "F", "I", "UP"]
86
+ ignore = ["E501"]
87
+
88
+ [tool.ruff.lint.per-file-ignores]
89
+ "__init__.py" = ["F401"]
90
+ "tests/*" = ["F403", "F405"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,3 @@
1
+ """CSRMesh protocol library."""
2
+
3
+ from .mesh import CSRMesh
@@ -0,0 +1,123 @@
1
+ """Fake BleakClient for replay testing."""
2
+
3
+ import asyncio
4
+ from collections.abc import Callable
5
+
6
+
7
+ class FakeBleakClient:
8
+ """
9
+ Device simulator for replay testing.
10
+
11
+ Acts like a real BleakClient: accepts writes, verifies against transcript,
12
+ delivers notifications to handlers.
13
+ """
14
+
15
+ def __init__(self, transcript: dict):
16
+ self.transcript = transcript
17
+ self.event_ptr = 0
18
+ self.notification_handlers: dict[str, Callable] = {}
19
+ self.connected = True
20
+
21
+ async def start_notify(self, char_uuid: str, callback: Callable):
22
+ """Register notification handler, skip CCCD events."""
23
+ self.notification_handlers[char_uuid] = callback
24
+
25
+ while self.event_ptr < len(self.transcript["events"]):
26
+ event = self.transcript["events"][self.event_ptr]
27
+ if event["type"] == "descriptor_write" and \
28
+ event["details"]["characteristic"] == char_uuid:
29
+ self.event_ptr += 1
30
+ else:
31
+ break
32
+
33
+ await self._replay_notifications()
34
+
35
+ async def write_gatt_char(
36
+ self,
37
+ char_uuid: str,
38
+ data: bytes,
39
+ response: bool = True
40
+ ):
41
+ """Verify write matches transcript, then replay device response."""
42
+ if self.event_ptr >= len(self.transcript["events"]):
43
+ raise RuntimeError(
44
+ f"State machine wrote beyond transcript end\n"
45
+ f" Characteristic: {char_uuid}\n"
46
+ f" Data: {data.hex()}"
47
+ )
48
+
49
+ event = self.transcript["events"][self.event_ptr]
50
+
51
+ if event["type"] != "gatt_write":
52
+ raise RuntimeError(
53
+ f"Protocol violation at event {self.event_ptr}:\n"
54
+ f" Expected: {event['type']} (state machine should be waiting)\n"
55
+ f" Got: gatt_write to {char_uuid}"
56
+ )
57
+
58
+ expected_char = event["details"]["characteristic"]
59
+ expected_data = bytes.fromhex(event["details"]["value"].replace(" ", "").replace("\n", ""))
60
+ expected_type = event["details"]["write_type"]
61
+ actual_type = "write_without_response" if not response else "write_with_response"
62
+
63
+ if char_uuid != expected_char:
64
+ raise AssertionError(
65
+ f"Write to wrong characteristic at event {self.event_ptr}:\n"
66
+ f" Expected: {expected_char}\n"
67
+ f" Got: {char_uuid}"
68
+ )
69
+
70
+ if data != expected_data:
71
+ raise AssertionError(
72
+ f"Write data mismatch at event {self.event_ptr}:\n"
73
+ f" Expected: {expected_data.hex()}\n"
74
+ f" Got: {data.hex()}"
75
+ )
76
+
77
+ if actual_type != expected_type:
78
+ raise AssertionError(
79
+ f"Write type mismatch at event {self.event_ptr}:\n"
80
+ f" Expected: {expected_type}\n"
81
+ f" Got: {actual_type}"
82
+ )
83
+
84
+ self.event_ptr += 1
85
+ await self._replay_notifications()
86
+
87
+ async def _replay_notifications(self):
88
+ """Deliver consecutive notification events to handlers."""
89
+ while self.event_ptr < len(self.transcript["events"]):
90
+ event = self.transcript["events"][self.event_ptr]
91
+ if event["type"] != "notification":
92
+ break
93
+
94
+ char_uuid = event["details"]["characteristic"]
95
+ data = bytes.fromhex(event["details"]["value"].replace(" ", "").replace("\n", ""))
96
+
97
+ handler = self.notification_handlers.get(char_uuid)
98
+ if not handler:
99
+ raise RuntimeError(
100
+ f"No handler registered for {char_uuid} at event {self.event_ptr}"
101
+ )
102
+
103
+ handler(None, bytearray(data))
104
+ self.event_ptr += 1
105
+ await asyncio.sleep(0.001)
106
+
107
+ async def disconnect(self):
108
+ self.connected = False
109
+
110
+ async def stop_notify(self, char_uuid: str):
111
+ pass
112
+
113
+ def verify_complete(self):
114
+ """Verify all transcript events were consumed."""
115
+ if self.event_ptr != len(self.transcript["events"]):
116
+ remaining = len(self.transcript["events"]) - self.event_ptr
117
+ next_event = self.transcript["events"][self.event_ptr]
118
+ raise AssertionError(
119
+ f"Transcript not fully replayed:\n"
120
+ f" Consumed: {self.event_ptr}/{len(self.transcript['events'])}\n"
121
+ f" Remaining: {remaining} events\n"
122
+ f" Next event: {next_event['type']}"
123
+ )
@@ -0,0 +1,194 @@
1
+ """BLE state machine for CSRMesh association."""
2
+
3
+ import asyncio
4
+ import logging
5
+ import time
6
+ from enum import IntEnum, auto
7
+
8
+ from .crypto import (
9
+ MASP_XOR_MASK,
10
+ add_packet_mac,
11
+ derive_key,
12
+ uuid_to_hash31,
13
+ verify_packet_mac,
14
+ xor_masp_packet,
15
+ )
16
+ from .masp import MaspOpcode
17
+ from .protocol import ProtocolState, ProtocolStateMachine
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+ # CSRMesh GATT Service
22
+ SERVICE_UUID = "c4edc000-9daf-11e3-8000-00025b000b00"
23
+
24
+ # MTL Characteristics (legacy)
25
+ CHARACTERISTIC_LOW = "c4edc000-9daf-11e3-8003-00025b000b00"
26
+ CHARACTERISTIC_HIGH = "c4edc000-9daf-11e3-8004-00025b000b00"
27
+
28
+ # CCCD Descriptor
29
+ CCCD_UUID = "00002902-0000-1000-8000-00805f9b34fb"
30
+
31
+
32
+ class AssociationState(IntEnum):
33
+ """Association session states."""
34
+ DISCONNECTED = auto()
35
+ CONNECTING = auto()
36
+ ASSOCIATING = auto()
37
+ COMPLETE = auto()
38
+ FAILED = auto()
39
+
40
+
41
+ class AssociationStateMachine:
42
+ """
43
+ MASP association protocol runner.
44
+
45
+ MTL reassembly and notification management are handled by CSRMesh.
46
+ Raw reassembled bytes arrive via feed_raw().
47
+ """
48
+
49
+ def __init__(
50
+ self,
51
+ client,
52
+ uuid_hash: int,
53
+ passphrase: str,
54
+ device_id: int | None = None,
55
+ ):
56
+ self.client = client
57
+ self.uuid_hash = uuid_hash
58
+ self.passphrase = passphrase
59
+
60
+ if device_id is None:
61
+ device_id = 33896
62
+
63
+ self.protocol = ProtocolStateMachine(uuid_hash, device_id, passphrase)
64
+
65
+ self.masp_key = derive_key("", "\x00MASP")
66
+
67
+ # State
68
+ self.state = AssociationState.DISCONNECTED
69
+ self.error: str | None = None
70
+ self.pending_response: bytes | None = None
71
+
72
+ def feed_raw(self, raw: bytes):
73
+ """Accept raw reassembled bytes from CSRMesh notification layer."""
74
+ payload, valid = verify_packet_mac(raw, self.masp_key)
75
+ if valid:
76
+ raw = payload
77
+ logger.debug(f"[MAC valid] payload {len(raw)}B")
78
+ else:
79
+ logger.debug(f"[MAC invalid] passing raw {len(raw)}B")
80
+ message = xor_masp_packet(raw)
81
+
82
+ opcode = message[0]
83
+ opname = MaspOpcode(opcode).name if opcode in MaspOpcode._value2member_map_ else f"0x{opcode:02x}"
84
+ logger.debug(f"[message] opcode={opname} ({len(message)}B)")
85
+ self.pending_response = message
86
+
87
+ async def run(self) -> bool:
88
+ """Execute full association sequence."""
89
+ try:
90
+ self.state = AssociationState.ASSOCIATING
91
+ await self._run_protocol()
92
+ return self.state == AssociationState.COMPLETE
93
+ except Exception as e:
94
+ self.error = str(e)
95
+ self.state = AssociationState.FAILED
96
+ return False
97
+
98
+ async def _run_protocol(self, retries: int = 3, timeout: float = 10.0):
99
+ """Execute MASP protocol state machine with per-message retries."""
100
+ request = self.protocol.get_initial_request()
101
+
102
+ while request is not None:
103
+ advanced = False
104
+ for attempt in range(retries + 1):
105
+ if attempt > 0:
106
+ logger.debug(f"[retry] attempt {attempt + 1}/{retries + 1}"
107
+ f" (state={self.protocol.state.name})")
108
+ assert request is not None
109
+ await self._send_masp_message(request)
110
+
111
+ deadline = time.time() + timeout
112
+ while True:
113
+ remaining = deadline - time.time()
114
+ if remaining <= 0:
115
+ break
116
+
117
+ response = await self._wait_for_response(timeout=remaining)
118
+ if response is None:
119
+ break
120
+
121
+ next_request = self.protocol.process(response)
122
+ if self.protocol.error:
123
+ raise RuntimeError(self.protocol.error)
124
+ if next_request is not None or self.protocol.state == ProtocolState.COMPLETE:
125
+ request = next_request
126
+ advanced = True
127
+ break
128
+
129
+ if advanced:
130
+ break
131
+ else:
132
+ raise TimeoutError(
133
+ f"No response from device after {retries + 1} attempts "
134
+ f"(state={self.protocol.state.name})")
135
+
136
+ if self.protocol.state == ProtocolState.COMPLETE:
137
+ self.state = AssociationState.COMPLETE
138
+ else:
139
+ raise RuntimeError(f"Protocol ended in state {self.protocol.state}")
140
+
141
+ async def _send_masp_message(self, message_after_xor: bytes):
142
+ """Send MASP message, fragmenting across characteristics if needed."""
143
+ # TTL=55 (0x37) matches Android app behavior
144
+ packet_with_mac = add_packet_mac(message_after_xor, self.masp_key, ttl=55)
145
+
146
+ xor_opcode = message_after_xor[0]
147
+ decoded_opcode = xor_opcode ^ MASP_XOR_MASK[0]
148
+ opname = MaspOpcode(decoded_opcode).name if decoded_opcode in MaspOpcode._value2member_map_ else f"0x{decoded_opcode:02x}"
149
+ logger.debug(f"[send] {opname} ({len(packet_with_mac)}B) wire={packet_with_mac.hex()}")
150
+
151
+ # Short packets (<=20B): write to 8004 only
152
+ # Long packets (>20B): first 20 to 8003, overflow to 8004
153
+ if len(packet_with_mac) <= 20:
154
+ await self.client.write_gatt_char(
155
+ CHARACTERISTIC_HIGH, packet_with_mac, response=False)
156
+ else:
157
+ chunk1 = packet_with_mac[:20]
158
+ chunk2 = packet_with_mac[20:]
159
+
160
+ await self.client.write_gatt_char(
161
+ CHARACTERISTIC_LOW, chunk1, response=False)
162
+
163
+ if chunk2:
164
+ await self.client.write_gatt_char(
165
+ CHARACTERISTIC_HIGH, chunk2, response=False)
166
+
167
+ async def _wait_for_response(self, timeout: float) -> bytes | None:
168
+ """Wait for complete response to arrive."""
169
+ start = time.time()
170
+ while self.pending_response is None:
171
+ if time.time() - start > timeout:
172
+ return None
173
+ await asyncio.sleep(0.01)
174
+
175
+ response = self.pending_response
176
+ self.pending_response = None
177
+ return response
178
+
179
+
180
+ def _process_discovery_packet(raw: bytes, masp_key: bytes, results: list):
181
+ """Process a received packet during discovery."""
182
+ payload, valid = verify_packet_mac(raw, masp_key)
183
+ if not valid:
184
+ return
185
+
186
+ message = xor_masp_packet(payload)
187
+ if len(message) < 17 or message[0] != MaspOpcode.UUID_ANNOUNCE:
188
+ return
189
+
190
+ uuid_bytes = message[1:17]
191
+ uuid_hash = uuid_to_hash31(uuid_bytes)
192
+ if not any(r['uuid_hash'] == uuid_hash for r in results):
193
+ results.append({'uuid': uuid_bytes, 'uuid_hash': uuid_hash})
194
+ logger.debug(f"[discovered] uuid_hash=0x{uuid_hash:08X} uuid={uuid_bytes.hex()}")