meshcore 2.3.17__tar.gz → 2.3.20__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.
- {meshcore-2.3.17 → meshcore-2.3.20}/PKG-INFO +1 -1
- {meshcore-2.3.17 → meshcore-2.3.20}/pyproject.toml +1 -1
- {meshcore-2.3.17 → meshcore-2.3.20}/src/meshcore/ble_cx.py +27 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/src/meshcore/commands/base.py +33 -6
- {meshcore-2.3.17 → meshcore-2.3.20}/src/meshcore/commands/binary.py +147 -1
- {meshcore-2.3.17 → meshcore-2.3.20}/src/meshcore/commands/contact.py +65 -55
- {meshcore-2.3.17 → meshcore-2.3.20}/src/meshcore/commands/device.py +90 -48
- {meshcore-2.3.17 → meshcore-2.3.20}/src/meshcore/commands/messaging.py +20 -21
- {meshcore-2.3.17 → meshcore-2.3.20}/src/meshcore/connection_manager.py +5 -1
- {meshcore-2.3.17 → meshcore-2.3.20}/src/meshcore/events.py +5 -3
- {meshcore-2.3.17 → meshcore-2.3.20}/src/meshcore/lpp_json_encoder.py +5 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/src/meshcore/meshcore.py +33 -4
- {meshcore-2.3.17 → meshcore-2.3.20}/src/meshcore/meshcore_parser.py +40 -13
- {meshcore-2.3.17 → meshcore-2.3.20}/src/meshcore/packets.py +4 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/src/meshcore/parsing.py +30 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/src/meshcore/reader.py +108 -45
- {meshcore-2.3.17 → meshcore-2.3.20}/src/meshcore/serial_cx.py +5 -3
- meshcore-2.3.20/tests/unit/test_anon_req_device_path.py +132 -0
- meshcore-2.3.20/tests/unit/test_ble_device_and_disconnect.py +118 -0
- meshcore-2.3.20/tests/unit/test_ble_dropped_client.py +130 -0
- meshcore-2.3.20/tests/unit/test_dispatcher_stop.py +55 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/tests/unit/test_error_handling.py +7 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/tests/unit/test_events.py +26 -0
- meshcore-2.3.20/tests/unit/test_keep_channel_secrets.py +83 -0
- meshcore-2.3.20/tests/unit/test_log_privacy.py +79 -0
- meshcore-2.3.20/tests/unit/test_parse_error_events.py +71 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/tests/unit/test_protocol_surface_gaps.py +76 -5
- meshcore-2.3.20/tests/unit/test_reader_frame_lengths.py +108 -0
- meshcore-2.3.20/tests/unit/test_request_helpers.py +104 -0
- meshcore-2.3.20/tests/unit/test_settings_without_appstart.py +103 -0
- meshcore-2.3.20/tests/unit/test_telemetry_partial_lpp.py +77 -0
- meshcore-2.3.20/tests/unit/test_update_contact_round_trip.py +111 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/.github/funding.yml +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/.github/python-test.yml +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/.github/workflows/python-import.yml +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/.gitignore +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/LICENSE +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/README.md +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/examples/.pubsub_example.py.swp +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/examples/ble_chat.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/examples/ble_pin_pairing_example.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/examples/ble_private_key_export.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/examples/ble_sign_example.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/examples/ble_stats.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/examples/ble_t1000_chan_msg.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/examples/ble_t1000_custom_vars.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/examples/ble_t1000_infos.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/examples/ble_t1000_msg.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/examples/ble_t1000_msg_retries.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/examples/ble_t1000_set_cv.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/examples/chan_recv_with_path.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/examples/connection_events_example.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/examples/mepo_mc_gps.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/examples/pubsub_example.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/examples/rf_packet_monitor.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/examples/serial_battery_monitor.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/examples/serial_channel_manager.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/examples/serial_chat.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/examples/serial_contacts.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/examples/serial_infos.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/examples/serial_meshcore_ollama.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/examples/serial_msg.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/examples/serial_pingbot.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/examples/serial_repeater_status.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/examples/serial_repeater_telemetry.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/examples/serial_rss_bot.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/examples/serial_trace.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/examples/tcp_chat.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/examples/tcp_login_status.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/examples/tcp_mchome_contacts.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/examples/tcp_mchome_infos.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/examples/tcp_mchome_msg.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/examples/tcp_mchome_readmsgs.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/pytest.ini +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/src/meshcore/__init__.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/src/meshcore/commands/__init__.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/src/meshcore/commands/control_data.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/src/meshcore/tcp_cx.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/tests/README.md +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/tests/test_ble_connection.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/tests/test_ble_pin_pairing.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/tests/test_meshcore_ble_pin.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/tests/unit/test_asyncio_lifecycle.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/tests/unit/test_ble_reconnect_cleanup.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/tests/unit/test_commands.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/tests/unit/test_connection_manager.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/tests/unit/test_lpp_parsing.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/tests/unit/test_parse_status.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/tests/unit/test_path_discovery_response.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/tests/unit/test_private_key_export.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/tests/unit/test_reader.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/tests/unit/test_rxlog_keyerror_regression.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/tests/unit/test_send_msg_with_retry.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/tests/unit/test_serial_connection.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/tests/unit/test_standalone_fixes.py +0 -0
- {meshcore-2.3.17 → meshcore-2.3.20}/tests/unit/test_transport_symmetry.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: meshcore
|
|
3
|
-
Version: 2.3.
|
|
3
|
+
Version: 2.3.20
|
|
4
4
|
Summary: Base classes for communicating with meshcore companion radios
|
|
5
5
|
Project-URL: Homepage, https://github.com/fdlamotte/meshcore_py
|
|
6
6
|
Project-URL: Issues, https://github.com/fdlamotte/meshcore_py/issues
|
|
@@ -32,6 +32,9 @@ class BLEConnection:
|
|
|
32
32
|
# measured 0.06-0.17s against real hardware; observed stalls ran 20s to
|
|
33
33
|
# minutes, so this preempts them rather than waiting for CoreBluetooth.
|
|
34
34
|
WRITE_TIMEOUT = 10.0
|
|
35
|
+
# Upper bound on releasing a client whose link dropped (see
|
|
36
|
+
# _release_dropped_client).
|
|
37
|
+
DISCONNECT_TIMEOUT = 10.0
|
|
35
38
|
|
|
36
39
|
def __init__(self, address=None, device=None, client=None, pin=None):
|
|
37
40
|
"""
|
|
@@ -104,6 +107,25 @@ class BLEConnection:
|
|
|
104
107
|
except Exception:
|
|
105
108
|
logger.debug("Best-effort cleanup of stale BLE client failed", exc_info=True)
|
|
106
109
|
|
|
110
|
+
async def _release_dropped_client(self, client):
|
|
111
|
+
"""Best-effort disconnect of a client whose link has dropped.
|
|
112
|
+
|
|
113
|
+
On Linux, bleak releases the D-Bus connection it opened for a link only
|
|
114
|
+
in disconnect(), not when the link drops. BlueZ keeps the notify
|
|
115
|
+
session that connection started and turns it back on at the next
|
|
116
|
+
connect, so every later notification would arrive once more for each
|
|
117
|
+
link that dropped before. With the link already down, disconnect()
|
|
118
|
+
leaves the device alone and only lets go of the bus.
|
|
119
|
+
|
|
120
|
+
Bounded: bleak's disconnect() never returns for a client whose own
|
|
121
|
+
D-Bus connection never came up, and is_connected is False for every
|
|
122
|
+
dropped client, so that can't be ruled out from here.
|
|
123
|
+
"""
|
|
124
|
+
try:
|
|
125
|
+
await asyncio.wait_for(client.disconnect(), timeout=self.DISCONNECT_TIMEOUT)
|
|
126
|
+
except Exception:
|
|
127
|
+
logger.debug("Best-effort release of dropped BLE client failed", exc_info=True)
|
|
128
|
+
|
|
107
129
|
async def connect(self):
|
|
108
130
|
"""
|
|
109
131
|
Connects to the device.
|
|
@@ -132,6 +154,7 @@ class BLEConnection:
|
|
|
132
154
|
elif self.device:
|
|
133
155
|
logger.debug("Directly using a passed device.")
|
|
134
156
|
self.client = BleakClient(self.device, disconnected_callback=self.handle_disconnect)
|
|
157
|
+
self.address = self.client.address
|
|
135
158
|
else:
|
|
136
159
|
|
|
137
160
|
def match_meshcore_device(d: BLEDevice, adv: AdvertisementData):
|
|
@@ -205,6 +228,10 @@ class BLEConnection:
|
|
|
205
228
|
logger.debug(
|
|
206
229
|
f"BLE device disconnected: {client.address} (is_connected: {client.is_connected})"
|
|
207
230
|
)
|
|
231
|
+
# Release the client that dropped -- the one bleak passes, not
|
|
232
|
+
# self.client -- so its notify session doesn't outlive the link.
|
|
233
|
+
self._spawn_background(self._release_dropped_client(client))
|
|
234
|
+
|
|
208
235
|
# Reset the address/client/device we found to what user specified
|
|
209
236
|
# this allows to reconnect to the same device
|
|
210
237
|
self.address = self._user_provided_address
|
|
@@ -130,6 +130,7 @@ class CommandHandlerBase:
|
|
|
130
130
|
self._sender_func: Optional[Callable[[bytes], Coroutine[Any, Any, None]]] = None
|
|
131
131
|
self._reader: Optional[MessageReader] = None
|
|
132
132
|
self.dispatcher: Optional[EventDispatcher] = None
|
|
133
|
+
self._get_self_info: Optional[Callable[[], Optional[Dict[str, Any]]]] = None
|
|
133
134
|
self.__mesh_request_lock: Optional[asyncio.Lock] = None
|
|
134
135
|
self.default_timeout = (
|
|
135
136
|
default_timeout if default_timeout is not None else self.DEFAULT_TIMEOUT
|
|
@@ -158,6 +159,10 @@ class CommandHandlerBase:
|
|
|
158
159
|
)-> None:
|
|
159
160
|
self._get_contact_by_prefix = func
|
|
160
161
|
|
|
162
|
+
def set_self_info_getter(self, func: Callable[[], Optional[Dict[str, Any]]]) -> None:
|
|
163
|
+
"""Give the handler the last SELF_INFO payload held, read at connect."""
|
|
164
|
+
self._get_self_info = func
|
|
165
|
+
|
|
161
166
|
async def wait_for_events(
|
|
162
167
|
self,
|
|
163
168
|
expected_events: Optional[Union[EventType, List[EventType]]] = None,
|
|
@@ -272,7 +277,7 @@ class CommandHandlerBase:
|
|
|
272
277
|
if self._sender_func:
|
|
273
278
|
logger.debug(
|
|
274
279
|
f"Sending raw data: "
|
|
275
|
-
f"{data.hex() if isinstance(data, bytes) else data}"
|
|
280
|
+
f"{data.hex() if isinstance(data, (bytes, bytearray)) else data}"
|
|
276
281
|
)
|
|
277
282
|
await self._sender_func(data)
|
|
278
283
|
|
|
@@ -316,7 +321,7 @@ class CommandHandlerBase:
|
|
|
316
321
|
if self._sender_func:
|
|
317
322
|
logger.debug(
|
|
318
323
|
f"Sending raw data: "
|
|
319
|
-
f"{data.hex() if isinstance(data, bytes) else data}"
|
|
324
|
+
f"{data.hex() if isinstance(data, (bytes, bytearray)) else data}"
|
|
320
325
|
)
|
|
321
326
|
await self._sender_func(data)
|
|
322
327
|
return Event(EventType.OK, {})
|
|
@@ -379,6 +384,26 @@ class CommandHandlerBase:
|
|
|
379
384
|
# asking a freshly discovered neighbour for its regions.
|
|
380
385
|
contact = self._get_contact_by_prefix(dst_bytes.hex())
|
|
381
386
|
|
|
387
|
+
device_contact = None
|
|
388
|
+
if contact is not None and contact["out_path_len"] == -1:
|
|
389
|
+
# This copy says flood, but it can be out of date: another app, or
|
|
390
|
+
# the device itself since the contacts were last read, may have
|
|
391
|
+
# given the device a path. Read the device's own record first, so
|
|
392
|
+
# that a path it holds is used, not replaced by zero-hop and then
|
|
393
|
+
# reset to flood at the end.
|
|
394
|
+
res = await self.get_contact_by_key(dst_bytes)
|
|
395
|
+
if res.type == EventType.NEXT_CONTACT and res.payload.get("public_key") == dst_bytes.hex():
|
|
396
|
+
device_contact = res.payload
|
|
397
|
+
for field in ("out_path", "out_path_len", "out_path_hash_mode"):
|
|
398
|
+
contact[field] = device_contact[field]
|
|
399
|
+
elif res.type == EventType.ERROR and res.payload.get("error_code") == 2:
|
|
400
|
+
# ERR_CODE_NOT_FOUND: the device doesn't hold it, so send as
|
|
401
|
+
# to any unknown destination rather than add it to the device.
|
|
402
|
+
contact = None
|
|
403
|
+
else:
|
|
404
|
+
logger.error("Could not read the contact from the device, aborting anon request")
|
|
405
|
+
return Event(EventType.ERROR, {"reason": "contact_read_failed"})
|
|
406
|
+
|
|
382
407
|
zero_hop = False
|
|
383
408
|
if contact is None:
|
|
384
409
|
logger.debug("No contact found, requesting a zero-hop direct reply path")
|
|
@@ -386,9 +411,12 @@ class CommandHandlerBase:
|
|
|
386
411
|
reply_path = encode_reply_path(0, "", 0)
|
|
387
412
|
else:
|
|
388
413
|
if contact["out_path_len"] == -1:
|
|
414
|
+
# The device holds it as flood too. Set zero-hop on the
|
|
415
|
+
# device's own record, so nothing else in it changes, and
|
|
416
|
+
# reset it to flood after sending.
|
|
389
417
|
logger.info("No path set trying zero hop")
|
|
390
418
|
zero_hop = True
|
|
391
|
-
path_res = await self.change_contact_path(
|
|
419
|
+
path_res = await self.change_contact_path(device_contact, "")
|
|
392
420
|
if path_res is not None and path_res.type == EventType.ERROR:
|
|
393
421
|
# The device still has this contact as flood, so sendAnonReq
|
|
394
422
|
# will flood the request -- and the server gates REGIONS,
|
|
@@ -397,9 +425,8 @@ class CommandHandlerBase:
|
|
|
397
425
|
# for a reply that cannot come.
|
|
398
426
|
logger.error("Could not set zero-hop path, aborting anon request")
|
|
399
427
|
return Event(EventType.ERROR, {"reason": "path_reset_failed"})
|
|
400
|
-
#
|
|
401
|
-
#
|
|
402
|
-
# device query inside it errored) the dict is still -1, and the unsigned
|
|
428
|
+
# After a zero-hop change, this dict still reads -1 (the change was
|
|
429
|
+
# reflected onto the device's record). Clamp it: the unsigned
|
|
403
430
|
# to_bytes below would raise OverflowError -- which would skip the
|
|
404
431
|
# reset_path at the end of this method and leave the contact pinned to
|
|
405
432
|
# zero-hop on the device. Zero is the right value to send regardless,
|
|
@@ -3,11 +3,14 @@ import logging
|
|
|
3
3
|
import random
|
|
4
4
|
import io
|
|
5
5
|
|
|
6
|
-
from .base import CommandHandlerBase
|
|
6
|
+
from .base import CommandHandlerBase, _validate_destination
|
|
7
7
|
from ..events import EventType
|
|
8
8
|
from ..packets import BinaryReqType
|
|
9
9
|
from ..packets import AnonReqType
|
|
10
10
|
|
|
11
|
+
from ..lpp_json_encoder import lpp_type_from_name
|
|
12
|
+
from cayennelpp import LppData
|
|
13
|
+
|
|
11
14
|
logger = logging.getLogger("meshcore")
|
|
12
15
|
|
|
13
16
|
|
|
@@ -245,6 +248,149 @@ class BinaryCommandHandler(CommandHandlerBase):
|
|
|
245
248
|
|
|
246
249
|
return res
|
|
247
250
|
|
|
251
|
+
async def _binary_req_response(self, contact, request_type, data=None, timeout=0, min_timeout=0):
|
|
252
|
+
"""Send a binary request and wait for its BINARY_RESPONSE.
|
|
253
|
+
|
|
254
|
+
Returns the response's data (after the tag), or None when the request
|
|
255
|
+
couldn't be sent or no answer came in time.
|
|
256
|
+
"""
|
|
257
|
+
res = await self.send_binary_req(
|
|
258
|
+
contact,
|
|
259
|
+
request_type,
|
|
260
|
+
data=data,
|
|
261
|
+
timeout=timeout,
|
|
262
|
+
min_timeout=min_timeout,
|
|
263
|
+
)
|
|
264
|
+
if res.type == EventType.ERROR:
|
|
265
|
+
return None
|
|
266
|
+
|
|
267
|
+
timeout = res.payload["suggested_timeout"] / 800 if timeout == 0 else timeout
|
|
268
|
+
timeout = timeout if timeout > min_timeout else min_timeout
|
|
269
|
+
|
|
270
|
+
if self.dispatcher is None:
|
|
271
|
+
return None
|
|
272
|
+
|
|
273
|
+
event = await self.dispatcher.wait_for_event(
|
|
274
|
+
EventType.BINARY_RESPONSE,
|
|
275
|
+
attribute_filters={"tag": res.payload["expected_ack"].hex()},
|
|
276
|
+
timeout=timeout,
|
|
277
|
+
)
|
|
278
|
+
return bytes.fromhex(event.payload["data"]) if event else None
|
|
279
|
+
|
|
280
|
+
async def req_owner_info_sync(self, contact, timeout=0, min_timeout=0):
|
|
281
|
+
"""Ask a repeater for its firmware version, name and owner info
|
|
282
|
+
(REQ_TYPE_GET_OWNER_INFO, repeater firmware at FIRMWARE_VER_LEVEL 2
|
|
283
|
+
and later). Needs a login to the repeater.
|
|
284
|
+
|
|
285
|
+
Returns a dict with "firmware_version", "name" and "owner", or None
|
|
286
|
+
with no answer.
|
|
287
|
+
"""
|
|
288
|
+
async with self._mesh_request_lock:
|
|
289
|
+
data = await self._binary_req_response(
|
|
290
|
+
contact, BinaryReqType.OWNER_INFO, timeout=timeout, min_timeout=min_timeout
|
|
291
|
+
)
|
|
292
|
+
if data is None:
|
|
293
|
+
return None
|
|
294
|
+
# "<version>\n<name>\n<owner info>", the owner info may itself hold
|
|
295
|
+
# newlines; the reply is padded with NULs to the cipher's block size
|
|
296
|
+
fields = data.decode("utf-8", "ignore").rstrip("\x00").split("\n", 2)
|
|
297
|
+
fields += [""] * (3 - len(fields))
|
|
298
|
+
return dict(firmware_version=fields[0], name=fields[1], owner=fields[2])
|
|
299
|
+
|
|
300
|
+
async def req_subscribe_sync(self, contact, push_tag: bytes, duration: int, min_deltas: bytes | dict | list[dict], timeout=0, min_timeout=0):
|
|
301
|
+
"""Subscribe to a sensor's telemetry pushes (REQ_TYPE_SUBSCRIBE,
|
|
302
|
+
simple_sensor firmware). Needs a login with at least read access.
|
|
303
|
+
|
|
304
|
+
Args:
|
|
305
|
+
push_tag: 4 bytes. Each push arrives as a BINARY_RESPONSE event
|
|
306
|
+
whose tag is this tag's hex, its data a 4-byte timestamp then
|
|
307
|
+
LPP readings.
|
|
308
|
+
duration: How long the subscription lasts, in seconds (16 bits).
|
|
309
|
+
min_deltas: The changes that trigger a push, LPP-encoded: for each
|
|
310
|
+
reading its channel, its LPP type and the least change, in that
|
|
311
|
+
type's encoding. 3 to 14 bytes.
|
|
312
|
+
can also be a list of dicts that will be encoded
|
|
313
|
+
|
|
314
|
+
Returns a dict with "expiry_secs" (0 when the sensor refused) and
|
|
315
|
+
"scope" (the region the pushes will be scoped to), or None with no
|
|
316
|
+
answer.
|
|
317
|
+
"""
|
|
318
|
+
if len(push_tag) != 4:
|
|
319
|
+
raise ValueError("push_tag must be 4 bytes")
|
|
320
|
+
|
|
321
|
+
if isinstance (min_deltas, dict):
|
|
322
|
+
if "lpp" in min_deltas:
|
|
323
|
+
min_deltas = min_deltas["lpp"]
|
|
324
|
+
else:
|
|
325
|
+
raise ValueError("min_deltas as a dict should have an lpp key")
|
|
326
|
+
|
|
327
|
+
if isinstance (min_deltas, list): # encode the array of dict as min_deltas
|
|
328
|
+
buf = bytearray()
|
|
329
|
+
for d in min_deltas:
|
|
330
|
+
channel = d["channel"]
|
|
331
|
+
datatype = d["type"]
|
|
332
|
+
value = d["value"]
|
|
333
|
+
if isinstance(datatype, str):
|
|
334
|
+
lpptype = lpp_type_from_name(datatype)
|
|
335
|
+
if lpptype is None:
|
|
336
|
+
raise ValueError(f"Unknown lpp type {datatype}")
|
|
337
|
+
datatype = lpptype
|
|
338
|
+
data = LppData(channel, datatype, (value))
|
|
339
|
+
buf.extend(data.to_bytes())
|
|
340
|
+
min_deltas = bytes(buf)
|
|
341
|
+
|
|
342
|
+
if not 3 <= len(min_deltas) <= 14:
|
|
343
|
+
raise ValueError("min_deltas must be 3 to 14 bytes")
|
|
344
|
+
|
|
345
|
+
req = (
|
|
346
|
+
bytes(push_tag)
|
|
347
|
+
+ duration.to_bytes(2, "little", signed=False)
|
|
348
|
+
+ b"\0" # reserved
|
|
349
|
+
+ len(min_deltas).to_bytes(1, "little")
|
|
350
|
+
+ bytes(min_deltas)
|
|
351
|
+
)
|
|
352
|
+
async with self._mesh_request_lock:
|
|
353
|
+
data = await self._binary_req_response(
|
|
354
|
+
contact, BinaryReqType.TELEM_SUBSCRIBE, data=req, timeout=timeout, min_timeout=min_timeout
|
|
355
|
+
)
|
|
356
|
+
if data is None:
|
|
357
|
+
return None
|
|
358
|
+
return dict(
|
|
359
|
+
expiry_secs=int.from_bytes(data[0:2], "little"),
|
|
360
|
+
scope=data[4:].decode("utf-8", "ignore").rstrip("\x00"),
|
|
361
|
+
)
|
|
362
|
+
|
|
363
|
+
async def telemetry_subscribe(self, contact, push_tag: bytes, duration: int, min_deltas: bytes | dict | list[dict], timeout=0, min_timeout=0):
|
|
364
|
+
""" subscribes to telemetry push and registers the tag for binary responses
|
|
365
|
+
"""
|
|
366
|
+
pubkey_prefix = _validate_destination(contact)
|
|
367
|
+
res = await self.req_subscribe_sync(contact, push_tag, duration, min_deltas, timeout, min_timeout)
|
|
368
|
+
|
|
369
|
+
if self._reader and res and res["expiry_secs"] > 0:
|
|
370
|
+
self._reader.register_binary_request(pubkey_prefix.hex(), push_tag.hex(), BinaryReqType.PUSHED_TELEMETRY, res["expiry_secs"], is_persistent=True)
|
|
371
|
+
|
|
372
|
+
return res
|
|
373
|
+
|
|
374
|
+
async def req_unsubscribe_sync(self, contact, timeout=0, min_timeout=0):
|
|
375
|
+
"""End a subscription to a sensor's telemetry pushes
|
|
376
|
+
(REQ_TYPE_UNSUBSCRIBE, simple_sensor firmware).
|
|
377
|
+
|
|
378
|
+
Returns True when the sensor answered, None with no answer.
|
|
379
|
+
"""
|
|
380
|
+
async with self._mesh_request_lock:
|
|
381
|
+
data = await self._binary_req_response(
|
|
382
|
+
contact, BinaryReqType.TELEM_UNSUBSCRIBE, timeout=timeout, min_timeout=min_timeout
|
|
383
|
+
)
|
|
384
|
+
|
|
385
|
+
# Unsubscribe any telemetry subscription in the reader
|
|
386
|
+
if self._reader:
|
|
387
|
+
p = _validate_destination(contact).hex()
|
|
388
|
+
for t, i in list(self._reader.pending_binary_requests.items()):
|
|
389
|
+
if i["request_type"] == BinaryReqType.PUSHED_TELEMETRY and i["pubkey_prefix"] == p:
|
|
390
|
+
del self._reader.pending_binary_requests[t]
|
|
391
|
+
|
|
392
|
+
return None if data is None else True
|
|
393
|
+
|
|
248
394
|
async def req_regions_async(self, contact, timeout=0, min_timeout=0):
|
|
249
395
|
req = b"\0" # The return path, I currently do nothing with, so direct only
|
|
250
396
|
return await self.send_anon_req(
|
|
@@ -8,6 +8,11 @@ from .base import CommandHandlerBase, DestinationType, _validate_destination
|
|
|
8
8
|
logger = logging.getLogger("meshcore")
|
|
9
9
|
|
|
10
10
|
|
|
11
|
+
def _decode_name(raw_hex: str) -> str:
|
|
12
|
+
"""A contact's name field decoded as the reader decodes it."""
|
|
13
|
+
return bytes.fromhex(raw_hex).decode("utf-8", "ignore").replace("\0", "")
|
|
14
|
+
|
|
15
|
+
|
|
11
16
|
class ContactCommands(CommandHandlerBase):
|
|
12
17
|
async def get_contacts_async(self, lastmod=0) :
|
|
13
18
|
logger.debug("Getting contacts")
|
|
@@ -18,60 +23,39 @@ class ContactCommands(CommandHandlerBase):
|
|
|
18
23
|
await self.send(data)
|
|
19
24
|
|
|
20
25
|
async def get_contacts(self, lastmod=0, timeout=5) -> Event:
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
)
|
|
32
|
-
futures.append(future)
|
|
33
|
-
|
|
34
|
-
while True:
|
|
26
|
+
loop = asyncio.get_running_loop()
|
|
27
|
+
result = loop.create_future()
|
|
28
|
+
state = {"activity": False}
|
|
29
|
+
|
|
30
|
+
def on_next(event):
|
|
31
|
+
state["activity"] = True
|
|
32
|
+
|
|
33
|
+
def on_end(event):
|
|
34
|
+
if not result.done():
|
|
35
|
+
result.set_result(event)
|
|
35
36
|
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
37
|
+
subs = [
|
|
38
|
+
self.dispatcher.subscribe(EventType.NEXT_CONTACT, on_next),
|
|
39
|
+
self.dispatcher.subscribe(EventType.CONTACTS, on_end),
|
|
40
|
+
self.dispatcher.subscribe(EventType.ERROR, on_end),
|
|
41
|
+
]
|
|
42
|
+
|
|
43
|
+
try:
|
|
44
|
+
await self.get_contacts_async(lastmod)
|
|
40
45
|
|
|
41
|
-
|
|
42
|
-
|
|
46
|
+
while True:
|
|
47
|
+
state["activity"] = False
|
|
48
|
+
try:
|
|
49
|
+
# shield so the timeout doesn't cancel the future itself
|
|
50
|
+
return await asyncio.wait_for(asyncio.shield(result), timeout)
|
|
51
|
+
except asyncio.TimeoutError:
|
|
52
|
+
if state["activity"]:
|
|
53
|
+
continue # still receiving contacts, keep waiting
|
|
43
54
|
logger.debug("Timeout while getting contacts")
|
|
44
|
-
for future in pending: # cancel all futures
|
|
45
|
-
future.cancel()
|
|
46
55
|
return Event(EventType.ERROR, {"reason": "timeout waiting for contacts"})
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
if event is None:
|
|
51
|
-
for f in pending:
|
|
52
|
-
f.cancel()
|
|
53
|
-
return Event(EventType.ERROR, {"reason": "no event received during contacts retrieval"})
|
|
54
|
-
if event.type != EventType.NEXT_CONTACT:
|
|
55
|
-
for f in pending:
|
|
56
|
-
f.cancel()
|
|
57
|
-
return event
|
|
58
|
-
|
|
59
|
-
futures = []
|
|
60
|
-
|
|
61
|
-
for future in pending: # put back pending
|
|
62
|
-
futures.append(future)
|
|
63
|
-
|
|
64
|
-
future = asyncio.create_task( # and recreate NEXT_CONTACT
|
|
65
|
-
self.dispatcher.wait_for_event(EventType.NEXT_CONTACT, {}, timeout)
|
|
66
|
-
)
|
|
67
|
-
futures.append(future)
|
|
68
|
-
|
|
69
|
-
except asyncio.TimeoutError:
|
|
70
|
-
logger.debug(f"Timeout receiving contacts")
|
|
71
|
-
return Event(EventType.ERROR, {"reason": "asyncio timeout receiving contacts"})
|
|
72
|
-
except Exception as e:
|
|
73
|
-
logger.debug(f"Command error: {e}")
|
|
74
|
-
return Event(EventType.ERROR, {"error": str(e)})
|
|
56
|
+
finally:
|
|
57
|
+
for s in subs:
|
|
58
|
+
s.unsubscribe()
|
|
75
59
|
|
|
76
60
|
async def reset_path(self, key: DestinationType) -> Event:
|
|
77
61
|
key_bytes = _validate_destination(key, prefix_length=32)
|
|
@@ -109,7 +93,12 @@ class ContactCommands(CommandHandlerBase):
|
|
|
109
93
|
data = b"\x0f" + key_bytes
|
|
110
94
|
return await self.send(data, [EventType.OK, EventType.ERROR])
|
|
111
95
|
|
|
112
|
-
async def update_contact(self, contact, path=None, flags=None, path_hash_mode=None) -> Event:
|
|
96
|
+
async def update_contact(self, contact, path=None, flags=None, path_hash_mode=None, lastmod=None) -> Event:
|
|
97
|
+
"""Write *contact* to the device (CMD_ADD_UPDATE_CONTACT).
|
|
98
|
+
|
|
99
|
+
*lastmod*, when given, is sent as the record's lastmod; without it
|
|
100
|
+
the device sets the record's lastmod to its own clock.
|
|
101
|
+
"""
|
|
113
102
|
if path is None:
|
|
114
103
|
out_path_hex = contact["out_path"]
|
|
115
104
|
out_path_len = contact["out_path_len"]
|
|
@@ -158,7 +147,13 @@ class ContactCommands(CommandHandlerBase):
|
|
|
158
147
|
# reflect the change
|
|
159
148
|
contact["flags"] = flags
|
|
160
149
|
|
|
161
|
-
|
|
150
|
+
raw_name = contact.get("adv_name_raw")
|
|
151
|
+
if raw_name is not None and _decode_name(raw_name) == contact["adv_name"]:
|
|
152
|
+
# The name as read, unchanged: write back its bytes as they were,
|
|
153
|
+
# not re-encoded from the decode, which drops a cut character.
|
|
154
|
+
adv_name_hex = raw_name
|
|
155
|
+
else:
|
|
156
|
+
adv_name_hex = contact["adv_name"].encode().hex()
|
|
162
157
|
adv_name_hex = adv_name_hex + (64 - len(adv_name_hex)) * "0"
|
|
163
158
|
data = (
|
|
164
159
|
b"\x09"
|
|
@@ -169,9 +164,13 @@ class ContactCommands(CommandHandlerBase):
|
|
|
169
164
|
+ bytes.fromhex(out_path_hex)
|
|
170
165
|
+ bytes.fromhex(adv_name_hex)
|
|
171
166
|
+ contact["last_advert"].to_bytes(4, "little")
|
|
172
|
-
|
|
173
|
-
|
|
167
|
+
# round, not int: the values were read as an integer / 1e6, and
|
|
168
|
+
# truncating gives some back one nearer zero
|
|
169
|
+
+ round(contact["adv_lat"] * 1e6).to_bytes(4, "little", signed=True)
|
|
170
|
+
+ round(contact["adv_lon"] * 1e6).to_bytes(4, "little", signed=True)
|
|
174
171
|
)
|
|
172
|
+
if lastmod is not None:
|
|
173
|
+
data += int(lastmod).to_bytes(4, "little")
|
|
175
174
|
return await self.send(data, [EventType.OK, EventType.ERROR])
|
|
176
175
|
|
|
177
176
|
async def add_contact(self, contact) -> Event:
|
|
@@ -183,11 +182,22 @@ class ContactCommands(CommandHandlerBase):
|
|
|
183
182
|
async def change_contact_flags(self, contact, flags) -> Event:
|
|
184
183
|
return await self.update_contact(contact, flags=flags)
|
|
185
184
|
|
|
186
|
-
async def set_autoadd_config(self, flag : int) -> Event:
|
|
185
|
+
async def set_autoadd_config(self, flag : int, max_hops: Optional[int] = None) -> Event:
|
|
186
|
+
"""Set which adverts the device adds as contacts by itself.
|
|
187
|
+
|
|
188
|
+
Args:
|
|
189
|
+
flag: The auto-add flags.
|
|
190
|
+
max_hops: The most hops an advert may have come to be added. The
|
|
191
|
+
firmware caps it at 64. Left as it is when None.
|
|
192
|
+
"""
|
|
187
193
|
data = b"\x3A" + flag.to_bytes(1, "little", signed=False)
|
|
194
|
+
if max_hops is not None:
|
|
195
|
+
data += max_hops.to_bytes(1, "little", signed=False)
|
|
188
196
|
return await self.send(data, [EventType.OK, EventType.ERROR])
|
|
189
197
|
|
|
190
198
|
async def get_autoadd_config(self) -> Event:
|
|
199
|
+
"""Read the auto-add flags ("config") and, from companion v1.14.0,
|
|
200
|
+
the hop limit ("max_hops")."""
|
|
191
201
|
data = b"\x3B"
|
|
192
202
|
return await self.send(data, [EventType.AUTOADD_CONFIG, EventType.ERROR])
|
|
193
203
|
|