meshcore 2.3.19__tar.gz → 2.3.21__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.
Files changed (96) hide show
  1. {meshcore-2.3.19 → meshcore-2.3.21}/PKG-INFO +1 -1
  2. {meshcore-2.3.19 → meshcore-2.3.21}/pyproject.toml +1 -1
  3. {meshcore-2.3.19 → meshcore-2.3.21}/src/meshcore/ble_cx.py +27 -0
  4. {meshcore-2.3.19 → meshcore-2.3.21}/src/meshcore/commands/base.py +33 -6
  5. {meshcore-2.3.19 → meshcore-2.3.21}/src/meshcore/commands/binary.py +187 -1
  6. {meshcore-2.3.19 → meshcore-2.3.21}/src/meshcore/commands/contact.py +36 -5
  7. {meshcore-2.3.19 → meshcore-2.3.21}/src/meshcore/commands/device.py +90 -48
  8. {meshcore-2.3.19 → meshcore-2.3.21}/src/meshcore/commands/messaging.py +1 -1
  9. {meshcore-2.3.19 → meshcore-2.3.21}/src/meshcore/connection_manager.py +5 -1
  10. {meshcore-2.3.19 → meshcore-2.3.21}/src/meshcore/events.py +5 -3
  11. {meshcore-2.3.19 → meshcore-2.3.21}/src/meshcore/lpp_json_encoder.py +5 -0
  12. {meshcore-2.3.19 → meshcore-2.3.21}/src/meshcore/meshcore.py +12 -0
  13. {meshcore-2.3.19 → meshcore-2.3.21}/src/meshcore/meshcore_parser.py +40 -13
  14. {meshcore-2.3.19 → meshcore-2.3.21}/src/meshcore/packets.py +4 -0
  15. {meshcore-2.3.19 → meshcore-2.3.21}/src/meshcore/parsing.py +30 -0
  16. {meshcore-2.3.19 → meshcore-2.3.21}/src/meshcore/reader.py +108 -45
  17. meshcore-2.3.21/tests/unit/test_anon_req_device_path.py +132 -0
  18. meshcore-2.3.21/tests/unit/test_ble_device_and_disconnect.py +118 -0
  19. meshcore-2.3.21/tests/unit/test_ble_dropped_client.py +130 -0
  20. meshcore-2.3.21/tests/unit/test_dispatcher_stop.py +55 -0
  21. {meshcore-2.3.19 → meshcore-2.3.21}/tests/unit/test_error_handling.py +7 -0
  22. {meshcore-2.3.19 → meshcore-2.3.21}/tests/unit/test_events.py +26 -0
  23. meshcore-2.3.21/tests/unit/test_keep_channel_secrets.py +83 -0
  24. meshcore-2.3.21/tests/unit/test_log_privacy.py +79 -0
  25. meshcore-2.3.21/tests/unit/test_parse_error_events.py +71 -0
  26. {meshcore-2.3.19 → meshcore-2.3.21}/tests/unit/test_protocol_surface_gaps.py +76 -5
  27. meshcore-2.3.21/tests/unit/test_reader_frame_lengths.py +108 -0
  28. meshcore-2.3.21/tests/unit/test_request_helpers.py +104 -0
  29. meshcore-2.3.21/tests/unit/test_settings_without_appstart.py +103 -0
  30. meshcore-2.3.21/tests/unit/test_telemetry_partial_lpp.py +77 -0
  31. meshcore-2.3.21/tests/unit/test_update_contact_round_trip.py +111 -0
  32. {meshcore-2.3.19 → meshcore-2.3.21}/.github/funding.yml +0 -0
  33. {meshcore-2.3.19 → meshcore-2.3.21}/.github/python-test.yml +0 -0
  34. {meshcore-2.3.19 → meshcore-2.3.21}/.github/workflows/python-import.yml +0 -0
  35. {meshcore-2.3.19 → meshcore-2.3.21}/.gitignore +0 -0
  36. {meshcore-2.3.19 → meshcore-2.3.21}/LICENSE +0 -0
  37. {meshcore-2.3.19 → meshcore-2.3.21}/README.md +0 -0
  38. {meshcore-2.3.19 → meshcore-2.3.21}/examples/.pubsub_example.py.swp +0 -0
  39. {meshcore-2.3.19 → meshcore-2.3.21}/examples/ble_chat.py +0 -0
  40. {meshcore-2.3.19 → meshcore-2.3.21}/examples/ble_pin_pairing_example.py +0 -0
  41. {meshcore-2.3.19 → meshcore-2.3.21}/examples/ble_private_key_export.py +0 -0
  42. {meshcore-2.3.19 → meshcore-2.3.21}/examples/ble_sign_example.py +0 -0
  43. {meshcore-2.3.19 → meshcore-2.3.21}/examples/ble_stats.py +0 -0
  44. {meshcore-2.3.19 → meshcore-2.3.21}/examples/ble_t1000_chan_msg.py +0 -0
  45. {meshcore-2.3.19 → meshcore-2.3.21}/examples/ble_t1000_custom_vars.py +0 -0
  46. {meshcore-2.3.19 → meshcore-2.3.21}/examples/ble_t1000_infos.py +0 -0
  47. {meshcore-2.3.19 → meshcore-2.3.21}/examples/ble_t1000_msg.py +0 -0
  48. {meshcore-2.3.19 → meshcore-2.3.21}/examples/ble_t1000_msg_retries.py +0 -0
  49. {meshcore-2.3.19 → meshcore-2.3.21}/examples/ble_t1000_set_cv.py +0 -0
  50. {meshcore-2.3.19 → meshcore-2.3.21}/examples/chan_recv_with_path.py +0 -0
  51. {meshcore-2.3.19 → meshcore-2.3.21}/examples/connection_events_example.py +0 -0
  52. {meshcore-2.3.19 → meshcore-2.3.21}/examples/mepo_mc_gps.py +0 -0
  53. {meshcore-2.3.19 → meshcore-2.3.21}/examples/pubsub_example.py +0 -0
  54. {meshcore-2.3.19 → meshcore-2.3.21}/examples/rf_packet_monitor.py +0 -0
  55. {meshcore-2.3.19 → meshcore-2.3.21}/examples/serial_battery_monitor.py +0 -0
  56. {meshcore-2.3.19 → meshcore-2.3.21}/examples/serial_channel_manager.py +0 -0
  57. {meshcore-2.3.19 → meshcore-2.3.21}/examples/serial_chat.py +0 -0
  58. {meshcore-2.3.19 → meshcore-2.3.21}/examples/serial_contacts.py +0 -0
  59. {meshcore-2.3.19 → meshcore-2.3.21}/examples/serial_infos.py +0 -0
  60. {meshcore-2.3.19 → meshcore-2.3.21}/examples/serial_meshcore_ollama.py +0 -0
  61. {meshcore-2.3.19 → meshcore-2.3.21}/examples/serial_msg.py +0 -0
  62. {meshcore-2.3.19 → meshcore-2.3.21}/examples/serial_pingbot.py +0 -0
  63. {meshcore-2.3.19 → meshcore-2.3.21}/examples/serial_repeater_status.py +0 -0
  64. {meshcore-2.3.19 → meshcore-2.3.21}/examples/serial_repeater_telemetry.py +0 -0
  65. {meshcore-2.3.19 → meshcore-2.3.21}/examples/serial_rss_bot.py +0 -0
  66. {meshcore-2.3.19 → meshcore-2.3.21}/examples/serial_trace.py +0 -0
  67. {meshcore-2.3.19 → meshcore-2.3.21}/examples/tcp_chat.py +0 -0
  68. {meshcore-2.3.19 → meshcore-2.3.21}/examples/tcp_login_status.py +0 -0
  69. {meshcore-2.3.19 → meshcore-2.3.21}/examples/tcp_mchome_contacts.py +0 -0
  70. {meshcore-2.3.19 → meshcore-2.3.21}/examples/tcp_mchome_infos.py +0 -0
  71. {meshcore-2.3.19 → meshcore-2.3.21}/examples/tcp_mchome_msg.py +0 -0
  72. {meshcore-2.3.19 → meshcore-2.3.21}/examples/tcp_mchome_readmsgs.py +0 -0
  73. {meshcore-2.3.19 → meshcore-2.3.21}/pytest.ini +0 -0
  74. {meshcore-2.3.19 → meshcore-2.3.21}/src/meshcore/__init__.py +0 -0
  75. {meshcore-2.3.19 → meshcore-2.3.21}/src/meshcore/commands/__init__.py +0 -0
  76. {meshcore-2.3.19 → meshcore-2.3.21}/src/meshcore/commands/control_data.py +0 -0
  77. {meshcore-2.3.19 → meshcore-2.3.21}/src/meshcore/serial_cx.py +0 -0
  78. {meshcore-2.3.19 → meshcore-2.3.21}/src/meshcore/tcp_cx.py +0 -0
  79. {meshcore-2.3.19 → meshcore-2.3.21}/tests/README.md +0 -0
  80. {meshcore-2.3.19 → meshcore-2.3.21}/tests/test_ble_connection.py +0 -0
  81. {meshcore-2.3.19 → meshcore-2.3.21}/tests/test_ble_pin_pairing.py +0 -0
  82. {meshcore-2.3.19 → meshcore-2.3.21}/tests/test_meshcore_ble_pin.py +0 -0
  83. {meshcore-2.3.19 → meshcore-2.3.21}/tests/unit/test_asyncio_lifecycle.py +0 -0
  84. {meshcore-2.3.19 → meshcore-2.3.21}/tests/unit/test_ble_reconnect_cleanup.py +0 -0
  85. {meshcore-2.3.19 → meshcore-2.3.21}/tests/unit/test_commands.py +0 -0
  86. {meshcore-2.3.19 → meshcore-2.3.21}/tests/unit/test_connection_manager.py +0 -0
  87. {meshcore-2.3.19 → meshcore-2.3.21}/tests/unit/test_lpp_parsing.py +0 -0
  88. {meshcore-2.3.19 → meshcore-2.3.21}/tests/unit/test_parse_status.py +0 -0
  89. {meshcore-2.3.19 → meshcore-2.3.21}/tests/unit/test_path_discovery_response.py +0 -0
  90. {meshcore-2.3.19 → meshcore-2.3.21}/tests/unit/test_private_key_export.py +0 -0
  91. {meshcore-2.3.19 → meshcore-2.3.21}/tests/unit/test_reader.py +0 -0
  92. {meshcore-2.3.19 → meshcore-2.3.21}/tests/unit/test_rxlog_keyerror_regression.py +0 -0
  93. {meshcore-2.3.19 → meshcore-2.3.21}/tests/unit/test_send_msg_with_retry.py +0 -0
  94. {meshcore-2.3.19 → meshcore-2.3.21}/tests/unit/test_serial_connection.py +0 -0
  95. {meshcore-2.3.19 → meshcore-2.3.21}/tests/unit/test_standalone_fixes.py +0 -0
  96. {meshcore-2.3.19 → meshcore-2.3.21}/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.19
3
+ Version: 2.3.21
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
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "meshcore"
7
- version = "2.3.19"
7
+ version = "2.3.21"
8
8
  authors = [
9
9
  { name="Florent de Lamotte", email="florent@frizoncorrea.fr" },
10
10
  { name="Alex Wolden", email="awolden@gmail.com" },
@@ -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(contact, "")
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
- # update_contact() normally reflects the change back onto the dict, so
401
- # out_path_len reads 0 here. Clamp anyway: if that call failed (e.g. the
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,189 @@ 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
+ if datatype == 136: # LPP_GPS: value is the min movement radius (m)
339
+ buf.extend(bytes([channel, datatype]))
340
+ buf.extend(int(round(value * 1000)).to_bytes(4, "big")) # metres -> mm
341
+ buf.extend(bytes(5)) # unused rest of the 9-byte slot
342
+ else:
343
+ data = LppData(channel, datatype, (value))
344
+ buf.extend(data.to_bytes())
345
+ min_deltas = bytes(buf)
346
+
347
+ if not 3 <= len(min_deltas) <= 14:
348
+ raise ValueError("min_deltas must be 3 to 14 bytes")
349
+
350
+ req = (
351
+ bytes(push_tag)
352
+ + duration.to_bytes(2, "little", signed=False)
353
+ + b"\0" # reserved
354
+ + len(min_deltas).to_bytes(1, "little")
355
+ + bytes(min_deltas)
356
+ )
357
+ async with self._mesh_request_lock:
358
+ data = await self._binary_req_response(
359
+ contact, BinaryReqType.TELEM_SUBSCRIBE, data=req, timeout=timeout, min_timeout=min_timeout
360
+ )
361
+ if data is None:
362
+ return None
363
+ return dict(
364
+ expiry_secs=int.from_bytes(data[0:2], "little"),
365
+ scope=data[4:].decode("utf-8", "ignore").rstrip("\x00"),
366
+ )
367
+
368
+ async def telemetry_subscribe(self, contact, duration: int, min_deltas: bytes | dict | list[dict],
369
+ push_tag: bytes | None = None, timeout=0, min_timeout=0):
370
+ """ subscribes to telemetry push and registers the tag for binary responses
371
+ """
372
+ pubkey_prefix = _validate_destination(contact)
373
+ res = await self.req_subscribe_sync(contact, push_tag, duration, min_deltas, timeout, min_timeout)
374
+
375
+ if push_tag is None:
376
+ push_tag = random.randbytes(4)
377
+ while reader and push_tag.hex() in reader.pending_binary_requests:
378
+ push_tag = random.randbytes(4)
379
+ elif len(push_tag) != 4:
380
+ raise ValueError("push_tag must be 4 bytes")
381
+ tag = push_tag.hex()
382
+
383
+ # register before sending, so a push that overtakes the reply
384
+ # is still attributed to its sender
385
+ if reader:
386
+ reader.register_binary_request(
387
+ pubkey_prefix, tag, BinaryReqType.PUSHED_TELEMETRY,
388
+ duration, is_persistent=True,
389
+ )
390
+
391
+ try:
392
+ res = await self.req_subscribe_sync(
393
+ contact, push_tag, duration, min_deltas, timeout, min_timeout
394
+ )
395
+ except BaseException:
396
+ if reader:
397
+ reader.pending_binary_requests.pop(tag, None)
398
+ raise
399
+
400
+ if res is None or res["expiry_secs"] == 0:
401
+ if reader:
402
+ reader.pending_binary_requests.pop(tag, None)
403
+ return res
404
+
405
+ if reader: # the sensor may have granted less than asked for
406
+ reader.register_binary_request(
407
+ pubkey_prefix, tag, BinaryReqType.PUSHED_TELEMETRY,
408
+ res["expiry_secs"], is_persistent=True,
409
+ )
410
+
411
+ res["push_tag"] = push_tag
412
+ return res
413
+
414
+ async def req_unsubscribe_sync(self, contact, timeout=0, min_timeout=0):
415
+ """End a subscription to a sensor's telemetry pushes
416
+ (REQ_TYPE_UNSUBSCRIBE, simple_sensor firmware).
417
+
418
+ Returns True when the sensor answered, None with no answer.
419
+ """
420
+ async with self._mesh_request_lock:
421
+ data = await self._binary_req_response(
422
+ contact, BinaryReqType.TELEM_UNSUBSCRIBE, timeout=timeout, min_timeout=min_timeout
423
+ )
424
+
425
+ # Unsubscribe any telemetry subscription in the reader
426
+ if self._reader:
427
+ p = _validate_destination(contact).hex()
428
+ for t, i in list(self._reader.pending_binary_requests.items()):
429
+ if i["request_type"] == BinaryReqType.PUSHED_TELEMETRY and i["pubkey_prefix"] == p:
430
+ del self._reader.pending_binary_requests[t]
431
+
432
+ return None if data is None else True
433
+
248
434
  async def req_regions_async(self, contact, timeout=0, min_timeout=0):
249
435
  req = b"\0" # The return path, I currently do nothing with, so direct only
250
436
  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")
@@ -88,7 +93,12 @@ class ContactCommands(CommandHandlerBase):
88
93
  data = b"\x0f" + key_bytes
89
94
  return await self.send(data, [EventType.OK, EventType.ERROR])
90
95
 
91
- 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
+ """
92
102
  if path is None:
93
103
  out_path_hex = contact["out_path"]
94
104
  out_path_len = contact["out_path_len"]
@@ -137,7 +147,13 @@ class ContactCommands(CommandHandlerBase):
137
147
  # reflect the change
138
148
  contact["flags"] = flags
139
149
 
140
- adv_name_hex = contact["adv_name"].encode().hex()
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()
141
157
  adv_name_hex = adv_name_hex + (64 - len(adv_name_hex)) * "0"
142
158
  data = (
143
159
  b"\x09"
@@ -148,9 +164,13 @@ class ContactCommands(CommandHandlerBase):
148
164
  + bytes.fromhex(out_path_hex)
149
165
  + bytes.fromhex(adv_name_hex)
150
166
  + contact["last_advert"].to_bytes(4, "little")
151
- + int(contact["adv_lat"] * 1e6).to_bytes(4, "little", signed=True)
152
- + int(contact["adv_lon"] * 1e6).to_bytes(4, "little", signed=True)
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)
153
171
  )
172
+ if lastmod is not None:
173
+ data += int(lastmod).to_bytes(4, "little")
154
174
  return await self.send(data, [EventType.OK, EventType.ERROR])
155
175
 
156
176
  async def add_contact(self, contact) -> Event:
@@ -162,11 +182,22 @@ class ContactCommands(CommandHandlerBase):
162
182
  async def change_contact_flags(self, contact, flags) -> Event:
163
183
  return await self.update_contact(contact, flags=flags)
164
184
 
165
- 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
+ """
166
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)
167
196
  return await self.send(data, [EventType.OK, EventType.ERROR])
168
197
 
169
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")."""
170
201
  data = b"\x3B"
171
202
  return await self.send(data, [EventType.AUTOADD_CONFIG, EventType.ERROR])
172
203
 
@@ -9,6 +9,16 @@ from .base import CommandHandlerBase, DestinationType, _validate_destination
9
9
 
10
10
  logger = logging.getLogger("meshcore")
11
11
 
12
+ # The SELF_INFO fields CMD_SET_OTHER_PARAMS writes
13
+ OTHER_PARAMS = (
14
+ "manual_add_contacts",
15
+ "telemetry_mode_base",
16
+ "telemetry_mode_loc",
17
+ "telemetry_mode_env",
18
+ "adv_loc_policy",
19
+ "multi_acks",
20
+ )
21
+
12
22
 
13
23
  class DeviceCommands(CommandHandlerBase):
14
24
  async def send_appstart(self, timeout=None) -> Event:
@@ -24,7 +34,7 @@ class DeviceCommands(CommandHandlerBase):
24
34
  return await self.send(b"\x16\x03", [EventType.DEVICE_INFO, EventType.ERROR])
25
35
 
26
36
  async def run_cli_command(self, cmd: str) -> Event:
27
- logger.debug(f"Sending cli command: {cmd}")
37
+ logger.debug("Sending cli command") # not the command: it can carry a password
28
38
  cmd_data = bytearray([CommandType.RUN_CLI_COMMAND.value])
29
39
  cmd_data.extend(cmd.encode("utf-8"))
30
40
  return await self.send(cmd_data, [EventType.CLI_REPLY, EventType.ERROR])
@@ -57,8 +67,8 @@ class DeviceCommands(CommandHandlerBase):
57
67
  logger.debug(f"Setting coordinates to: lat={lat}, lon={lon}")
58
68
  return await self.send(
59
69
  b"\x0e"
60
- + int(lat * 1e6).to_bytes(4, "little", signed=True)
61
- + int(lon * 1e6).to_bytes(4, "little", signed=True)
70
+ + round(lat * 1e6).to_bytes(4, "little", signed=True)
71
+ + round(lon * 1e6).to_bytes(4, "little", signed=True)
62
72
  + int(0).to_bytes(4, "little"),
63
73
  [EventType.OK, EventType.ERROR],
64
74
  )
@@ -132,7 +142,16 @@ class DeviceCommands(CommandHandlerBase):
132
142
  + telemetry_mode.to_bytes(1, "little")
133
143
  + advert_loc_policy.to_bytes(1, "little")
134
144
  )
135
- return await self.send(data, [EventType.OK, EventType.ERROR])
145
+ result = await self.send(data, [EventType.OK, EventType.ERROR])
146
+ if result.type == EventType.OK:
147
+ self._remember_other_params({
148
+ "manual_add_contacts": manual_add_contacts,
149
+ "telemetry_mode_base": telemetry_mode_base & 0b11,
150
+ "telemetry_mode_loc": telemetry_mode_loc & 0b11,
151
+ "telemetry_mode_env": telemetry_mode_env & 0b11,
152
+ "adv_loc_policy": advert_loc_policy,
153
+ })
154
+ return result
136
155
 
137
156
  async def set_other_params_from_infos(self, infos) -> Event:
138
157
  telemetry_mode = (
@@ -147,58 +166,73 @@ class DeviceCommands(CommandHandlerBase):
147
166
  + infos["adv_loc_policy"].to_bytes(1, "little")
148
167
  + infos["multi_acks"].to_bytes(1, "little")
149
168
  )
150
- return await self.send(data, [EventType.OK, EventType.ERROR])
169
+ result = await self.send(data, [EventType.OK, EventType.ERROR])
170
+ if result.type == EventType.OK:
171
+ self._remember_other_params({
172
+ "manual_add_contacts": infos["manual_add_contacts"],
173
+ "telemetry_mode_base": infos["telemetry_mode_base"] & 0b11,
174
+ "telemetry_mode_loc": infos["telemetry_mode_loc"] & 0b11,
175
+ "telemetry_mode_env": infos["telemetry_mode_env"] & 0b11,
176
+ "adv_loc_policy": infos["adv_loc_policy"],
177
+ "multi_acks": infos["multi_acks"],
178
+ })
179
+ return result
151
180
 
152
- async def set_telemetry_mode_base(self, telemetry_mode_base: int) -> Event:
153
- result = await self.send_appstart()
154
- if result.is_error():
155
- return result
156
- infos = result.payload
157
- infos["telemetry_mode_base"] = telemetry_mode_base
181
+ def _held_self_info(self):
182
+ getter = getattr(self, "_get_self_info", None)
183
+ return getter() if getter else None
184
+
185
+ def _remember_other_params(self, params) -> None:
186
+ """Update the held self info with settings the device has taken, so
187
+ the next single-setting call doesn't put back an old value."""
188
+ held = self._held_self_info()
189
+ if held is not None:
190
+ held.update(params)
191
+
192
+ async def _set_other_param(self, key: str, value) -> Event:
193
+ """Change one of the settings CMD_SET_OTHER_PARAMS writes, keeping
194
+ the others as they are.
195
+
196
+ The others are taken from the self info already held (read by
197
+ APP_START when connecting), not read again with APP_START: the
198
+ firmware's APP_START also stops a contact list it is sending
199
+ (_iter_started = false), so a get_contacts in progress, this
200
+ client's or another's on the same device, would never end. APP_START
201
+ is sent only when no self info is held. Held values are kept up to
202
+ date by the setters here; a change made by another client since the
203
+ last APP_START is not seen.
204
+ """
205
+ held = self._held_self_info()
206
+ if held and all(k in held for k in OTHER_PARAMS):
207
+ infos = {k: held[k] for k in OTHER_PARAMS}
208
+ else:
209
+ result = await self.send_appstart()
210
+ if result.is_error():
211
+ return result
212
+ infos = result.payload
213
+ infos[key] = value
158
214
  return await self.set_other_params_from_infos(infos)
159
215
 
216
+ async def set_telemetry_mode_base(self, telemetry_mode_base: int) -> Event:
217
+ return await self._set_other_param("telemetry_mode_base", telemetry_mode_base)
218
+
160
219
  async def set_telemetry_mode_loc(self, telemetry_mode_loc: int) -> Event:
161
- result = await self.send_appstart()
162
- if result.is_error():
163
- return result
164
- infos = result.payload
165
- infos["telemetry_mode_loc"] = telemetry_mode_loc
166
- return await self.set_other_params_from_infos(infos)
220
+ return await self._set_other_param("telemetry_mode_loc", telemetry_mode_loc)
167
221
 
168
222
  async def set_telemetry_mode_env(self, telemetry_mode_env: int) -> Event:
169
- result = await self.send_appstart()
170
- if result.is_error():
171
- return result
172
- infos = result.payload
173
- infos["telemetry_mode_env"] = telemetry_mode_env
174
- return await self.set_other_params_from_infos(infos)
223
+ return await self._set_other_param("telemetry_mode_env", telemetry_mode_env)
175
224
 
176
225
  async def set_manual_add_contacts(self, manual_add_contacts: bool) -> Event:
177
- result = await self.send_appstart()
178
- if result.is_error():
179
- return result
180
- infos = result.payload
181
- infos["manual_add_contacts"] = manual_add_contacts
182
- return await self.set_other_params_from_infos(infos)
226
+ return await self._set_other_param("manual_add_contacts", manual_add_contacts)
183
227
 
184
228
  async def set_advert_loc_policy(self, advert_loc_policy: int) -> Event:
185
- result = await self.send_appstart()
186
- if result.is_error():
187
- return result
188
- infos = result.payload
189
- infos["adv_loc_policy"] = advert_loc_policy
190
- return await self.set_other_params_from_infos(infos)
229
+ return await self._set_other_param("adv_loc_policy", advert_loc_policy)
191
230
 
192
231
  async def set_multi_acks(self, multi_acks: int) -> Event:
193
- result = await self.send_appstart()
194
- if result.is_error():
195
- return result
196
- infos = result.payload
197
- infos["multi_acks"] = multi_acks
198
- return await self.set_other_params_from_infos(infos)
232
+ return await self._set_other_param("multi_acks", multi_acks)
199
233
 
200
234
  async def set_devicepin(self, pin: int) -> Event:
201
- logger.debug(f"Setting device PIN to: {pin}")
235
+ logger.debug("Setting device PIN")
202
236
  return await self.send(
203
237
  b"\x25" + int(pin).to_bytes(4, "little"), [EventType.OK, EventType.ERROR]
204
238
  )
@@ -312,15 +346,23 @@ class DeviceCommands(CommandHandlerBase):
312
346
 
313
347
  return await self.sign_finish(timeout=timeout, data_size=len(data))
314
348
 
315
- async def has_connection(self) -> Event:
316
- """N09: Check if the device has an active connection (CMD 28).
349
+ async def has_connection(self, dst: DestinationType) -> Event:
350
+ """N09: Check whether the device holds a connection to *dst* (CMD 28).
351
+
352
+ A connection is the keep-alive the device keeps with a server it has
353
+ logged in to (a room server, for instance). The firmware handles the
354
+ command only with the server's 32-byte public key after it.
355
+
356
+ Args:
357
+ dst: The server, as a contact, a public key or its hex.
317
358
 
318
359
  Returns:
319
- Event with a 1-byte response indicating connection status,
320
- or ERROR.
360
+ OK if the device holds a connection to *dst*, ERROR
361
+ (ERR_CODE_NOT_FOUND) if not.
321
362
  """
322
- logger.debug("Checking device connection status")
323
- return await self.send(b"\x1c", [EventType.OK, EventType.ERROR])
363
+ dst_bytes = _validate_destination(dst, prefix_length=32)
364
+ logger.debug(f"Checking connection to {dst_bytes.hex()}")
365
+ return await self.send(b"\x1c" + dst_bytes, [EventType.OK, EventType.ERROR])
324
366
 
325
367
  async def get_tuning(self) -> Event:
326
368
  """N03/N09: Request current tuning parameters (CMD_GET_TUNING_PARAMS = 43).
@@ -67,7 +67,7 @@ class MessagingCommands(CommandHandlerBase):
67
67
  dst_type = None # if None, will have to get a contact to know this
68
68
  ) -> Event:
69
69
  dst_bytes = _validate_destination(dst)
70
- logger.debug(f"Sending command to {dst_bytes.hex()}: {cmd}")
70
+ logger.debug(f"Sending command to {dst_bytes.hex()}") # not the command: it can carry a password
71
71
 
72
72
  if timestamp is None:
73
73
  import time
@@ -89,8 +89,12 @@ class ConnectionManager:
89
89
  pass
90
90
  self._reconnect_task = None
91
91
 
92
+ # Close the transport even when not marked connected: a link can be
93
+ # open after a connect() that returned None once it was up, or after
94
+ # handle_disconnect() marked it lost on a failed write. Each
95
+ # transport's disconnect() does nothing on a closed link.
96
+ await self.connection.disconnect()
92
97
  if self._is_connected:
93
- await self.connection.disconnect()
94
98
  self._is_connected = False
95
99
  await self._emit_event(
96
100
  EventType.DISCONNECTED, {"reason": "manual_disconnect"}