meshcore 2.3.22__tar.gz → 2.3.23__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 (99) hide show
  1. {meshcore-2.3.22 → meshcore-2.3.23}/PKG-INFO +45 -6
  2. {meshcore-2.3.22 → meshcore-2.3.23}/README.md +43 -5
  3. {meshcore-2.3.22 → meshcore-2.3.23}/examples/ble_pin_pairing_example.py +8 -1
  4. {meshcore-2.3.22 → meshcore-2.3.23}/pyproject.toml +2 -2
  5. {meshcore-2.3.22 → meshcore-2.3.23}/src/meshcore/ble_cx.py +123 -5
  6. meshcore-2.3.23/src/meshcore/ble_pairing.py +461 -0
  7. {meshcore-2.3.22 → meshcore-2.3.23}/src/meshcore/commands/messaging.py +4 -7
  8. {meshcore-2.3.22 → meshcore-2.3.23}/src/meshcore/meshcore.py +18 -0
  9. {meshcore-2.3.22 → meshcore-2.3.23}/src/meshcore/meshcore_parser.py +62 -2
  10. {meshcore-2.3.22 → meshcore-2.3.23}/src/meshcore/reader.py +14 -2
  11. meshcore-2.3.23/tests/test_ble_pairing.py +800 -0
  12. {meshcore-2.3.22 → meshcore-2.3.23}/tests/test_ble_pin_pairing.py +13 -1
  13. meshcore-2.3.23/tests/unit/test_message_scope.py +282 -0
  14. {meshcore-2.3.22 → meshcore-2.3.23}/.github/funding.yml +0 -0
  15. {meshcore-2.3.22 → meshcore-2.3.23}/.github/python-test.yml +0 -0
  16. {meshcore-2.3.22 → meshcore-2.3.23}/.github/workflows/python-import.yml +0 -0
  17. {meshcore-2.3.22 → meshcore-2.3.23}/.gitignore +0 -0
  18. {meshcore-2.3.22 → meshcore-2.3.23}/LICENSE +0 -0
  19. {meshcore-2.3.22 → meshcore-2.3.23}/examples/.pubsub_example.py.swp +0 -0
  20. {meshcore-2.3.22 → meshcore-2.3.23}/examples/ble_chat.py +0 -0
  21. {meshcore-2.3.22 → meshcore-2.3.23}/examples/ble_private_key_export.py +0 -0
  22. {meshcore-2.3.22 → meshcore-2.3.23}/examples/ble_sign_example.py +0 -0
  23. {meshcore-2.3.22 → meshcore-2.3.23}/examples/ble_stats.py +0 -0
  24. {meshcore-2.3.22 → meshcore-2.3.23}/examples/ble_t1000_chan_msg.py +0 -0
  25. {meshcore-2.3.22 → meshcore-2.3.23}/examples/ble_t1000_custom_vars.py +0 -0
  26. {meshcore-2.3.22 → meshcore-2.3.23}/examples/ble_t1000_infos.py +0 -0
  27. {meshcore-2.3.22 → meshcore-2.3.23}/examples/ble_t1000_msg.py +0 -0
  28. {meshcore-2.3.22 → meshcore-2.3.23}/examples/ble_t1000_msg_retries.py +0 -0
  29. {meshcore-2.3.22 → meshcore-2.3.23}/examples/ble_t1000_set_cv.py +0 -0
  30. {meshcore-2.3.22 → meshcore-2.3.23}/examples/chan_recv_with_path.py +0 -0
  31. {meshcore-2.3.22 → meshcore-2.3.23}/examples/connection_events_example.py +0 -0
  32. {meshcore-2.3.22 → meshcore-2.3.23}/examples/mepo_mc_gps.py +0 -0
  33. {meshcore-2.3.22 → meshcore-2.3.23}/examples/pubsub_example.py +0 -0
  34. {meshcore-2.3.22 → meshcore-2.3.23}/examples/rf_packet_monitor.py +0 -0
  35. {meshcore-2.3.22 → meshcore-2.3.23}/examples/serial_battery_monitor.py +0 -0
  36. {meshcore-2.3.22 → meshcore-2.3.23}/examples/serial_channel_manager.py +0 -0
  37. {meshcore-2.3.22 → meshcore-2.3.23}/examples/serial_chat.py +0 -0
  38. {meshcore-2.3.22 → meshcore-2.3.23}/examples/serial_contacts.py +0 -0
  39. {meshcore-2.3.22 → meshcore-2.3.23}/examples/serial_infos.py +0 -0
  40. {meshcore-2.3.22 → meshcore-2.3.23}/examples/serial_meshcore_ollama.py +0 -0
  41. {meshcore-2.3.22 → meshcore-2.3.23}/examples/serial_msg.py +0 -0
  42. {meshcore-2.3.22 → meshcore-2.3.23}/examples/serial_pingbot.py +0 -0
  43. {meshcore-2.3.22 → meshcore-2.3.23}/examples/serial_repeater_status.py +0 -0
  44. {meshcore-2.3.22 → meshcore-2.3.23}/examples/serial_repeater_telemetry.py +0 -0
  45. {meshcore-2.3.22 → meshcore-2.3.23}/examples/serial_rss_bot.py +0 -0
  46. {meshcore-2.3.22 → meshcore-2.3.23}/examples/serial_trace.py +0 -0
  47. {meshcore-2.3.22 → meshcore-2.3.23}/examples/tcp_chat.py +0 -0
  48. {meshcore-2.3.22 → meshcore-2.3.23}/examples/tcp_login_status.py +0 -0
  49. {meshcore-2.3.22 → meshcore-2.3.23}/examples/tcp_mchome_contacts.py +0 -0
  50. {meshcore-2.3.22 → meshcore-2.3.23}/examples/tcp_mchome_infos.py +0 -0
  51. {meshcore-2.3.22 → meshcore-2.3.23}/examples/tcp_mchome_msg.py +0 -0
  52. {meshcore-2.3.22 → meshcore-2.3.23}/examples/tcp_mchome_readmsgs.py +0 -0
  53. {meshcore-2.3.22 → meshcore-2.3.23}/pytest.ini +0 -0
  54. {meshcore-2.3.22 → meshcore-2.3.23}/src/meshcore/__init__.py +0 -0
  55. {meshcore-2.3.22 → meshcore-2.3.23}/src/meshcore/commands/__init__.py +0 -0
  56. {meshcore-2.3.22 → meshcore-2.3.23}/src/meshcore/commands/base.py +0 -0
  57. {meshcore-2.3.22 → meshcore-2.3.23}/src/meshcore/commands/binary.py +0 -0
  58. {meshcore-2.3.22 → meshcore-2.3.23}/src/meshcore/commands/contact.py +0 -0
  59. {meshcore-2.3.22 → meshcore-2.3.23}/src/meshcore/commands/control_data.py +0 -0
  60. {meshcore-2.3.22 → meshcore-2.3.23}/src/meshcore/commands/device.py +0 -0
  61. {meshcore-2.3.22 → meshcore-2.3.23}/src/meshcore/connection_manager.py +0 -0
  62. {meshcore-2.3.22 → meshcore-2.3.23}/src/meshcore/events.py +0 -0
  63. {meshcore-2.3.22 → meshcore-2.3.23}/src/meshcore/lpp_json_encoder.py +0 -0
  64. {meshcore-2.3.22 → meshcore-2.3.23}/src/meshcore/packets.py +0 -0
  65. {meshcore-2.3.22 → meshcore-2.3.23}/src/meshcore/parsing.py +0 -0
  66. {meshcore-2.3.22 → meshcore-2.3.23}/src/meshcore/serial_cx.py +0 -0
  67. {meshcore-2.3.22 → meshcore-2.3.23}/src/meshcore/tcp_cx.py +0 -0
  68. {meshcore-2.3.22 → meshcore-2.3.23}/tests/README.md +0 -0
  69. {meshcore-2.3.22 → meshcore-2.3.23}/tests/test_ble_connection.py +0 -0
  70. {meshcore-2.3.22 → meshcore-2.3.23}/tests/test_meshcore_ble_pin.py +0 -0
  71. {meshcore-2.3.22 → meshcore-2.3.23}/tests/unit/test_anon_req_device_path.py +0 -0
  72. {meshcore-2.3.22 → meshcore-2.3.23}/tests/unit/test_asyncio_lifecycle.py +0 -0
  73. {meshcore-2.3.22 → meshcore-2.3.23}/tests/unit/test_ble_device_and_disconnect.py +0 -0
  74. {meshcore-2.3.22 → meshcore-2.3.23}/tests/unit/test_ble_dropped_client.py +0 -0
  75. {meshcore-2.3.22 → meshcore-2.3.23}/tests/unit/test_ble_reconnect_cleanup.py +0 -0
  76. {meshcore-2.3.22 → meshcore-2.3.23}/tests/unit/test_commands.py +0 -0
  77. {meshcore-2.3.22 → meshcore-2.3.23}/tests/unit/test_connection_manager.py +0 -0
  78. {meshcore-2.3.22 → meshcore-2.3.23}/tests/unit/test_dispatcher_stop.py +0 -0
  79. {meshcore-2.3.22 → meshcore-2.3.23}/tests/unit/test_error_handling.py +0 -0
  80. {meshcore-2.3.22 → meshcore-2.3.23}/tests/unit/test_events.py +0 -0
  81. {meshcore-2.3.22 → meshcore-2.3.23}/tests/unit/test_keep_channel_secrets.py +0 -0
  82. {meshcore-2.3.22 → meshcore-2.3.23}/tests/unit/test_log_privacy.py +0 -0
  83. {meshcore-2.3.22 → meshcore-2.3.23}/tests/unit/test_lpp_parsing.py +0 -0
  84. {meshcore-2.3.22 → meshcore-2.3.23}/tests/unit/test_parse_error_events.py +0 -0
  85. {meshcore-2.3.22 → meshcore-2.3.23}/tests/unit/test_parse_status.py +0 -0
  86. {meshcore-2.3.22 → meshcore-2.3.23}/tests/unit/test_path_discovery_response.py +0 -0
  87. {meshcore-2.3.22 → meshcore-2.3.23}/tests/unit/test_private_key_export.py +0 -0
  88. {meshcore-2.3.22 → meshcore-2.3.23}/tests/unit/test_protocol_surface_gaps.py +0 -0
  89. {meshcore-2.3.22 → meshcore-2.3.23}/tests/unit/test_reader.py +0 -0
  90. {meshcore-2.3.22 → meshcore-2.3.23}/tests/unit/test_reader_frame_lengths.py +0 -0
  91. {meshcore-2.3.22 → meshcore-2.3.23}/tests/unit/test_request_helpers.py +0 -0
  92. {meshcore-2.3.22 → meshcore-2.3.23}/tests/unit/test_rxlog_keyerror_regression.py +0 -0
  93. {meshcore-2.3.22 → meshcore-2.3.23}/tests/unit/test_send_msg_with_retry.py +0 -0
  94. {meshcore-2.3.22 → meshcore-2.3.23}/tests/unit/test_serial_connection.py +0 -0
  95. {meshcore-2.3.22 → meshcore-2.3.23}/tests/unit/test_settings_without_appstart.py +0 -0
  96. {meshcore-2.3.22 → meshcore-2.3.23}/tests/unit/test_standalone_fixes.py +0 -0
  97. {meshcore-2.3.22 → meshcore-2.3.23}/tests/unit/test_telemetry_partial_lpp.py +0 -0
  98. {meshcore-2.3.22 → meshcore-2.3.23}/tests/unit/test_transport_symmetry.py +0 -0
  99. {meshcore-2.3.22 → meshcore-2.3.23}/tests/unit/test_update_contact_round_trip.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: meshcore
3
- Version: 2.3.22
3
+ Version: 2.3.23
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
@@ -11,6 +11,7 @@ Classifier: Operating System :: OS Independent
11
11
  Classifier: Programming Language :: Python :: 3
12
12
  Requires-Python: >=3.10
13
13
  Requires-Dist: bleak
14
+ Requires-Dist: dbus-fast; sys_platform == 'linux'
14
15
  Requires-Dist: pycayennelpp
15
16
  Requires-Dist: pycryptodome
16
17
  Requires-Dist: pyserial-asyncio-fast
@@ -151,13 +152,17 @@ meshcore = await MeshCore.create_ble("12:34:56:78:90:AB", pin="123456")
151
152
  ```
152
153
 
153
154
  **PIN Pairing Features:**
154
- - Automatic pairing initiation when PIN is provided
155
- - Graceful fallback if pairing fails (connection continues if device is already paired)
156
- - Compatible with all BLE connection methods (address, scanning, pre-configured client)
157
- - Logging of pairing success/failure for debugging
155
+ - Automatic pairing when a PIN is provided; pairing is skipped if the radio is already bonded
156
+ - On Linux/BlueZ the PIN is answered by a short-lived BlueZ agent that the library registers on its own D-Bus connection for one `Device1.Pair` call (it is never made the default agent, so it does not interfere with a desktop agent). Pairing completes before notifications start, then the library connects normally.
157
+ - Works with an address, a name scan, a `BLEDevice`, or a `BleakClient` that is not yet connected. A client that is already connected when `connect()` is called is not paired.
158
+ - A wrong PIN raises (`BlePairingError`, with the BlueZ error name in `.dbus_error`); `AuthenticationFailed` is never retried. One retry is made if the radio could not be reached at all, and the connect that follows a successful pairing is retried once if the link fails to come up (the radio is already bonded then; if the retry also fails `BleConnectAfterPairingError` is raised).
159
+ - The PIN must be 1 to 6 digits and is never logged. **Behaviour change:** on Linux an invalid PIN (for example `"abc"` or more than 6 digits) now raises `ValueError` from `connect()` before any scan; previously it was silently ignored. Other platforms are unchanged.
160
+ - An existing bond is never removed automatically. Connecting to a bonded radio can fail without a retry (the link drops right after it comes up); the error reports the connect failure and suggests trying again. If it keeps failing and the radio was reset or its PIN changed, the bond may be stale: remove it with `bluetoothctl remove <address>` and connect again.
161
+ - If the system D-Bus, BlueZ or `dbus-fast` is unavailable, or the agent cannot be registered, the library logs why and falls back to the previous behaviour (bleak's own `pair()`).
158
162
 
159
163
  **Note:** BLE pairing behavior may vary by platform:
160
- - **Linux/Windows**: PIN pairing is fully supported
164
+ - **Linux (BlueZ)**: passkey pairing is handled by the library as described above
165
+ - **Windows**: bleak's `pair()` is used
161
166
  - **macOS**: Pairing may be handled automatically by the system UI
162
167
 
163
168
  #### Auto-Reconnect and Connection Events
@@ -457,6 +462,40 @@ async def channel_handler(event):
457
462
  meshcore.subscribe(EventType.CHANNEL_MSG_RECV, channel_handler)
458
463
  ```
459
464
 
465
+ ### Message Scope
466
+
467
+ A scoped flood carries a 4-byte transport code; the first two bytes are
468
+ HMAC-SHA256(key, payload_type || payload)[:2], where the key is
469
+ SHA256("#name")[:16]. Register the scopes your bot uses and received packets are
470
+ matched against them:
471
+
472
+ ```python
473
+ meshcore.set_known_scopes(["#north", "south"]) # replaces the list; "#" optional
474
+ meshcore.add_known_scope("east") # or add_known_scope("name", key=<16 bytes>)
475
+ meshcore.clear_known_scopes()
476
+
477
+ async def on_msg(event):
478
+ scope = event.payload.get("scope") # "#north", or None
479
+ if scope: await meshcore.commands.set_flood_scope(scope) # reply in the same scope
480
+ meshcore.subscribe(EventType.CHANNEL_MSG_RECV, on_msg)
481
+ meshcore.subscribe(EventType.CHANNEL_MSG_RECV, on_msg, {"scope": "#north"}) # or filter
482
+ ```
483
+
484
+ Fields on `RX_LOG_DATA` payloads, and on `CHANNEL_MSG_RECV` payloads when
485
+ `set_decrypt_channel_logs(True)` and the message is matched to its RX log entry:
486
+
487
+ | Packet | `transport_code` | `scope` | `scope_matches` |
488
+ |--------|------------------|---------|-----------------|
489
+ | unscoped (no transport code) | absent on RX log (`None` on a channel message) | `None` (absent on RX log) | `None` (absent on RX log) |
490
+ | scoped, no known scope matches | 4 bytes, hex | `None` | `[]` |
491
+ | scoped, one known scope matches | 4 bytes, hex | `"#name"` | `["#name"]` |
492
+ | scoped, several match (16-bit codes can collide) | 4 bytes, hex | `None` | all matching `"#name"`s |
493
+
494
+ On a channel message these keys are *absent* when no RX log entry was found (or
495
+ decryption is off), so absent never means unscoped. The `scope` event attribute
496
+ is set only when exactly one scope matched. Direct messages (`CONTACT_MSG_RECV`)
497
+ have no RX log correlation and so carry no scope.
498
+
460
499
  ## API Reference
461
500
 
462
501
  ### Event Types
@@ -128,13 +128,17 @@ meshcore = await MeshCore.create_ble("12:34:56:78:90:AB", pin="123456")
128
128
  ```
129
129
 
130
130
  **PIN Pairing Features:**
131
- - Automatic pairing initiation when PIN is provided
132
- - Graceful fallback if pairing fails (connection continues if device is already paired)
133
- - Compatible with all BLE connection methods (address, scanning, pre-configured client)
134
- - Logging of pairing success/failure for debugging
131
+ - Automatic pairing when a PIN is provided; pairing is skipped if the radio is already bonded
132
+ - On Linux/BlueZ the PIN is answered by a short-lived BlueZ agent that the library registers on its own D-Bus connection for one `Device1.Pair` call (it is never made the default agent, so it does not interfere with a desktop agent). Pairing completes before notifications start, then the library connects normally.
133
+ - Works with an address, a name scan, a `BLEDevice`, or a `BleakClient` that is not yet connected. A client that is already connected when `connect()` is called is not paired.
134
+ - A wrong PIN raises (`BlePairingError`, with the BlueZ error name in `.dbus_error`); `AuthenticationFailed` is never retried. One retry is made if the radio could not be reached at all, and the connect that follows a successful pairing is retried once if the link fails to come up (the radio is already bonded then; if the retry also fails `BleConnectAfterPairingError` is raised).
135
+ - The PIN must be 1 to 6 digits and is never logged. **Behaviour change:** on Linux an invalid PIN (for example `"abc"` or more than 6 digits) now raises `ValueError` from `connect()` before any scan; previously it was silently ignored. Other platforms are unchanged.
136
+ - An existing bond is never removed automatically. Connecting to a bonded radio can fail without a retry (the link drops right after it comes up); the error reports the connect failure and suggests trying again. If it keeps failing and the radio was reset or its PIN changed, the bond may be stale: remove it with `bluetoothctl remove <address>` and connect again.
137
+ - If the system D-Bus, BlueZ or `dbus-fast` is unavailable, or the agent cannot be registered, the library logs why and falls back to the previous behaviour (bleak's own `pair()`).
135
138
 
136
139
  **Note:** BLE pairing behavior may vary by platform:
137
- - **Linux/Windows**: PIN pairing is fully supported
140
+ - **Linux (BlueZ)**: passkey pairing is handled by the library as described above
141
+ - **Windows**: bleak's `pair()` is used
138
142
  - **macOS**: Pairing may be handled automatically by the system UI
139
143
 
140
144
  #### Auto-Reconnect and Connection Events
@@ -434,6 +438,40 @@ async def channel_handler(event):
434
438
  meshcore.subscribe(EventType.CHANNEL_MSG_RECV, channel_handler)
435
439
  ```
436
440
 
441
+ ### Message Scope
442
+
443
+ A scoped flood carries a 4-byte transport code; the first two bytes are
444
+ HMAC-SHA256(key, payload_type || payload)[:2], where the key is
445
+ SHA256("#name")[:16]. Register the scopes your bot uses and received packets are
446
+ matched against them:
447
+
448
+ ```python
449
+ meshcore.set_known_scopes(["#north", "south"]) # replaces the list; "#" optional
450
+ meshcore.add_known_scope("east") # or add_known_scope("name", key=<16 bytes>)
451
+ meshcore.clear_known_scopes()
452
+
453
+ async def on_msg(event):
454
+ scope = event.payload.get("scope") # "#north", or None
455
+ if scope: await meshcore.commands.set_flood_scope(scope) # reply in the same scope
456
+ meshcore.subscribe(EventType.CHANNEL_MSG_RECV, on_msg)
457
+ meshcore.subscribe(EventType.CHANNEL_MSG_RECV, on_msg, {"scope": "#north"}) # or filter
458
+ ```
459
+
460
+ Fields on `RX_LOG_DATA` payloads, and on `CHANNEL_MSG_RECV` payloads when
461
+ `set_decrypt_channel_logs(True)` and the message is matched to its RX log entry:
462
+
463
+ | Packet | `transport_code` | `scope` | `scope_matches` |
464
+ |--------|------------------|---------|-----------------|
465
+ | unscoped (no transport code) | absent on RX log (`None` on a channel message) | `None` (absent on RX log) | `None` (absent on RX log) |
466
+ | scoped, no known scope matches | 4 bytes, hex | `None` | `[]` |
467
+ | scoped, one known scope matches | 4 bytes, hex | `"#name"` | `["#name"]` |
468
+ | scoped, several match (16-bit codes can collide) | 4 bytes, hex | `None` | all matching `"#name"`s |
469
+
470
+ On a channel message these keys are *absent* when no RX log entry was found (or
471
+ decryption is off), so absent never means unscoped. The `scope` event attribute
472
+ is set only when exactly one scope matched. Direct messages (`CONTACT_MSG_RECV`)
473
+ have no RX log correlation and so carry no scope.
474
+
437
475
  ## API Reference
438
476
 
439
477
  ### Event Types
@@ -4,6 +4,13 @@ Example: BLE PIN Pairing with MeshCore
4
4
 
5
5
  This example demonstrates how to connect to a MeshCore device using BLE
6
6
  with PIN-based pairing for enhanced security.
7
+
8
+ On Linux/BlueZ the library answers the radio's passkey request itself: it
9
+ registers a short-lived BlueZ agent on its own D-Bus connection around one
10
+ Device1.Pair call, then connects. No bluetoothctl agent or desktop pairing
11
+ dialog is needed. If the radio is already bonded, pairing is skipped. A stale
12
+ bond (radio reset or PIN changed) is never removed automatically; remove it
13
+ with `bluetoothctl remove <address>` and run again.
7
14
  """
8
15
 
9
16
  import asyncio
@@ -22,7 +29,7 @@ async def main():
22
29
  try:
23
30
  print("Connecting to MeshCore device...")
24
31
  if args.pin:
25
- print(f"Using PIN for pairing: {args.pin}")
32
+ print("Using a PIN for pairing")
26
33
 
27
34
  # Create BLE connection with optional PIN
28
35
  meshcore = await MeshCore.create_ble(
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "meshcore"
7
- version = "2.3.22"
7
+ version = "2.3.23"
8
8
  authors = [
9
9
  { name="Florent de Lamotte", email="florent@frizoncorrea.fr" },
10
10
  { name="Alex Wolden", email="awolden@gmail.com" },
@@ -18,7 +18,7 @@ classifiers = [
18
18
  ]
19
19
  license = "MIT"
20
20
  license-files = ["LICEN[CS]E*"]
21
- dependencies = [ "bleak", "pyserial-asyncio-fast", "pycayennelpp", "pycryptodome" ]
21
+ dependencies = [ "bleak", "dbus-fast; sys_platform == 'linux'", "pyserial-asyncio-fast", "pycayennelpp", "pycryptodome" ]
22
22
 
23
23
  [project.optional-dependencies]
24
24
  dev = ["pytest", "pytest-asyncio", "black", "ruff"]
@@ -6,6 +6,8 @@ import asyncio
6
6
  import logging
7
7
  from typing import Optional
8
8
 
9
+ from . import ble_pairing
10
+
9
11
 
10
12
  # Make bleak optional - only fail if BLE operations are attempted
11
13
  try:
@@ -13,12 +15,13 @@ try:
13
15
  from bleak.backends.characteristic import BleakGATTCharacteristic
14
16
  from bleak.backends.device import BLEDevice
15
17
  from bleak.backends.scanner import AdvertisementData
16
- from bleak.exc import BleakDeviceNotFoundError
18
+ from bleak.exc import BleakDBusError, BleakDeviceNotFoundError
17
19
  BLEAK_AVAILABLE = True
18
20
  except ImportError:
19
21
  BLEAK_AVAILABLE = False
20
22
  BleakClient = None
21
23
  BleakGATTCharacteristic = None
24
+ BleakDBusError = None
22
25
 
23
26
  # Get logger
24
27
  logger = logging.getLogger("meshcore")
@@ -27,6 +30,33 @@ UART_SERVICE_UUID = "6E400001-B5A3-F393-E0A9-E50E24DCCA9E"
27
30
  UART_RX_CHAR_UUID = "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"
28
31
  UART_TX_CHAR_UUID = "6E400003-B5A3-F393-E0A9-E50E24DCCA9E"
29
32
 
33
+ class BleConnectAfterPairingError(ConnectionError):
34
+ """Pairing succeeded but the connection could not be established, twice.
35
+
36
+ The radio is bonded; trying again normally works. Never contains the PIN.
37
+ """
38
+
39
+
40
+ def _link_not_established(exc: BaseException) -> bool:
41
+ """True for failures that mean the link to the radio never came up.
42
+
43
+ That includes bleak's AttributeError ("'NoneType' object has no attribute
44
+ 'call'") raised when the link drops while connect() is still running.
45
+ Authentication errors and cancellation are never retried.
46
+ """
47
+ if isinstance(exc, AttributeError):
48
+ return "NoneType" in str(exc)
49
+ if BleakDBusError is not None and isinstance(exc, BleakDBusError):
50
+ text = str(exc).lower()
51
+ if "authentication" in text:
52
+ return False
53
+ return any(k in text for k in (
54
+ "connectionattemptfailed", "failed to be established",
55
+ "page timeout", "le-connection-abort-by-local",
56
+ ))
57
+ return False
58
+
59
+
30
60
  class BLEConnection:
31
61
  # Upper bound on a single write (lock acquisition included). Healthy writes
32
62
  # measured 0.06-0.17s against real hardware; observed stalls ran 20s to
@@ -35,6 +65,8 @@ class BLEConnection:
35
65
  # Upper bound on releasing a client whose link dropped (see
36
66
  # _release_dropped_client).
37
67
  DISCONNECT_TIMEOUT = 10.0
68
+ # Upper bound on the one connect retry made right after a successful pairing.
69
+ CONNECT_RETRY_TIMEOUT = 30.0
38
70
 
39
71
  def __init__(self, address=None, device=None, client=None, pin=None):
40
72
  """
@@ -44,7 +76,12 @@ class BLEConnection:
44
76
  address (str, optional): The Bluetooth address of the device.
45
77
  device (BLEDevice, optional): A BLEDevice instance.
46
78
  client (BleakClient, optional): An existing BleakClient instance.
47
- pin (str, optional): PIN for BLE pairing authentication.
79
+ pin (str, optional): PIN for BLE pairing authentication. On
80
+ Linux/BlueZ the PIN is answered by a short-lived agent that is
81
+ registered on our own D-Bus connection for the duration of one
82
+ Device1.Pair call (see ble_pairing). It is applied only before
83
+ a connection is made: a BleakClient that is already connected
84
+ when connect() is called is returned as-is and is not paired.
48
85
  """
49
86
  if not BLEAK_AVAILABLE:
50
87
  raise ImportError(
@@ -138,12 +175,19 @@ class BLEConnection:
138
175
  """
139
176
  logger.debug(f"Connecting with client: {self.client}, address: {self.address}, device: {self.device}")
140
177
 
178
+ # Validate early, before any scan or D-Bus work. Other platforms ignore
179
+ # the PIN for pairing, so they keep their existing behaviour.
180
+ if self.pin is not None and ble_pairing.is_supported_platform():
181
+ ble_pairing.validate_pin(self.pin)
182
+
141
183
  await self._cleanup_stale_client()
142
184
 
143
185
  if self.client:
144
186
  logger.debug("Using pre-configured BleakClient.")
145
187
  assert isinstance(self.client, BleakClient)
146
188
  if self.client.is_connected :
189
+ if self.pin is not None:
190
+ logger.info("Client is already connected; the PIN is not used to pair it")
147
191
  logger.error("Client is already connected !!! weird")
148
192
  self.address = self.client.address
149
193
  return self.address
@@ -183,11 +227,21 @@ class BLEConnection:
183
227
  self.address, disconnected_callback=self.handle_disconnect
184
228
  )
185
229
 
230
+ # Linux/BlueZ: pair first, through an agent on our own D-Bus connection,
231
+ # then let bleak connect. pair() therefore completes before start_notify.
232
+ pairing = None
233
+ if self.pin is not None:
234
+ pairing = await ble_pairing.pair_with_passkey(self.client.address, self.pin)
235
+ agent_handled = pairing in (
236
+ ble_pairing.PairingOutcome.PAIRED,
237
+ ble_pairing.PairingOutcome.ALREADY_BONDED,
238
+ )
239
+
186
240
  try:
187
- await self.client.connect()
241
+ await self._connect_client(pairing)
188
242
 
189
- # Perform pairing if PIN is provided
190
- if self.pin is not None:
243
+ # Fallback: bleak's own pairing when the agent path could not be used
244
+ if self.pin is not None and not agent_handled:
191
245
  logger.debug(f"Attempting BLE pairing with PIN")
192
246
  try:
193
247
  await self.client.pair()
@@ -204,6 +258,9 @@ class BLEConnection:
204
258
  return None
205
259
  except TimeoutError:
206
260
  return None
261
+ except Exception as exc:
262
+ self._warn_if_stale_bond(pairing, exc)
263
+ raise
207
264
 
208
265
  try:
209
266
  await self.client.start_notify(UART_TX_CHAR_UUID, self.handle_rx)
@@ -213,6 +270,9 @@ class BLEConnection:
213
270
  logger.info("Connection is not established, need to restart it")
214
271
  logger.debug("in ble_cx.connect()")
215
272
  return None
273
+ except Exception as exc:
274
+ self._warn_if_stale_bond(pairing, exc)
275
+ raise
216
276
 
217
277
  nus = self.client.services.get_service(UART_SERVICE_UUID)
218
278
  if nus is None:
@@ -223,6 +283,64 @@ class BLEConnection:
223
283
  logger.info("BLE Connection started")
224
284
  return self.address
225
285
 
286
+ async def _connect_client(self, pairing):
287
+ """client.connect(), with one retry only right after this call paired.
288
+
289
+ The retry applies only when pairing just succeeded (not for an existing
290
+ bond, not without a PIN) and only for failures meaning the link never
291
+ came up (see _link_not_established). The failed client is disconnected,
292
+ we wait until the radio advertises again, and a fresh client is used.
293
+ """
294
+ failed = self.client
295
+ address = failed.address
296
+ try:
297
+ await failed.connect()
298
+ return
299
+ except Exception as first:
300
+ if pairing is not ble_pairing.PairingOutcome.PAIRED or not _link_not_established(first):
301
+ raise
302
+ first_err = f"{type(first).__name__}: {first}"
303
+ logger.warning("BLE connect right after pairing failed (%s); retrying once", first_err)
304
+ try:
305
+ await asyncio.wait_for(failed.disconnect(), self.DISCONNECT_TIMEOUT)
306
+ except Exception:
307
+ logger.debug("Best-effort disconnect of the failed client failed", exc_info=True)
308
+ await ble_pairing.wait_until_advertising(address)
309
+ # handle_disconnect() may already have reset self.client/self.address.
310
+ self.address = address
311
+ self.client = BleakClient(self.device or address, disconnected_callback=self.handle_disconnect)
312
+ try:
313
+ await asyncio.wait_for(self.client.connect(), self.CONNECT_RETRY_TIMEOUT)
314
+ except Exception as second:
315
+ second_err = f"{type(second).__name__}: {second}"
316
+ logger.error(
317
+ "BLE connect failed twice after a successful pairing (first: %s; retry: %s)",
318
+ first_err, second_err,
319
+ )
320
+ try:
321
+ await asyncio.wait_for(self.client.disconnect(), self.DISCONNECT_TIMEOUT)
322
+ except Exception:
323
+ pass
324
+ raise BleConnectAfterPairingError(
325
+ "Pairing succeeded but connecting failed twice "
326
+ f"(first: {first_err}; retry: {second_err}). The radio is bonded; try again."
327
+ ) from second
328
+ logger.info("BLE connect succeeded on the retry after pairing")
329
+
330
+ @staticmethod
331
+ def _warn_if_stale_bond(pairing, error):
332
+ """Log a failed connect on an existing bond. Never removes the bond."""
333
+ if pairing is ble_pairing.PairingOutcome.ALREADY_BONDED:
334
+ logger.error(
335
+ f"Connecting failed ({type(error).__name__}: {error}). "
336
+ "BlueZ already holds a bond for this device, so pairing was skipped. "
337
+ "A failed connect on an existing bond is often transient: try again. "
338
+ "If it keeps failing and the radio was reset, re-flashed or its PIN "
339
+ "changed, the bond may be stale: remove it (for example "
340
+ "'bluetoothctl remove <address>') and connect again. "
341
+ "The bond is not removed automatically."
342
+ )
343
+
226
344
  def handle_disconnect(self, client: BleakClient):
227
345
  """Callback to handle disconnection"""
228
346
  logger.debug(