-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathZeroComm_nodeSetup.py
More file actions
2303 lines (1936 loc) Β· 101 KB
/
ZeroComm_nodeSetup.py
File metadata and controls
2303 lines (1936 loc) Β· 101 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
MESHTASTIC BLE ADMIN TOOL
ZeroComm Fleet Configuration Utility
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Uses the official Meshtastic protobuf schemas (via the meshtastic PyPI
package) for all encoding and decoding. No manual protobuf parsing.
Requirements:
pip install bleak meshtastic
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
"""
import asyncio
import argparse
import base64
import hashlib
import json
import os
import random
import signal
import struct
import sys
import time
from dataclasses import dataclass, field
from datetime import datetime
from typing import Optional, List, Dict, Any
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# PROTOBUF IMPORTS (official Meshtastic schemas)
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
from meshtastic.protobuf import (
mesh_pb2,
config_pb2,
channel_pb2,
admin_pb2,
portnums_pb2,
module_config_pb2,
)
from bleak import BleakClient, BleakScanner
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# DEBUG CONFIGURATION
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
DEBUG_BLE = True
DEBUG_PROTO = True
DEBUG_DRAIN = True
DEBUG_ADMIN = True
def _ts():
return datetime.now().strftime("%H:%M:%S.%f")[:-3]
def debug_ble(msg):
if DEBUG_BLE: print(f" [{_ts()}] [BLE] {msg}")
def debug_proto(msg):
if DEBUG_PROTO: print(f" [{_ts()}] [PROTO] {msg}")
def debug_drain(msg):
if DEBUG_DRAIN: print(f" [{_ts()}] [DRAIN] {msg}")
def debug_admin(msg):
if DEBUG_ADMIN: print(f" [{_ts()}] [ADMIN] {msg}")
def info(msg):
print(f" {msg}")
def ok(msg):
print(f" β {msg}")
def err(msg):
print(f" β {msg}")
def warn(msg):
print(f" β {msg}")
def section(title):
print(f"\n{'β'*60}")
print(f" {title}")
print(f"{'β'*60}")
def subsection(title):
print(f"\n ββ {title} ββ")
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# BLE UUIDS
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
MESHTASTIC_SERVICE_UUID = "6ba1b218-15a8-461f-9fa8-5dcae273eafd"
TORADIO_UUID = "f75c76d2-129e-4dad-a1dd-7866124401e7"
FROMRADIO_UUID = "2c55e69e-4993-11ed-b878-0242ac120002"
FROMNUM_UUID = "ed9da18c-a800-4f66-a670-aa7547e34453"
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# TIMING CONSTANTS
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
SCAN_TIMEOUT = 10
CONNECT_TIMEOUT = 30
DRAIN_TIMEOUT = 45
REBOOT_WAIT = 7
RECONNECT_DELAY = 5
POST_WRITE_DELAY = 0.5
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# ENUM LOOKUPS
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
REGION_NAMES = {v.number: v.name
for v in config_pb2.Config.LoRaConfig.RegionCode.DESCRIPTOR.values}
MODEM_PRESET_NAMES = {v.number: v.name
for v in config_pb2.Config.LoRaConfig.ModemPreset.DESCRIPTOR.values}
DEVICE_ROLE_NAMES = {v.number: v.name
for v in config_pb2.Config.DeviceConfig.Role.DESCRIPTOR.values}
GPS_MODE_NAMES = {v.number: v.name
for v in config_pb2.Config.PositionConfig.GpsMode.DESCRIPTOR.values}
BT_MODE_NAMES = {v.number: v.name
for v in config_pb2.Config.BluetoothConfig.PairingMode.DESCRIPTOR.values}
CHANNEL_ROLE_NAMES = {v.number: v.name
for v in channel_pb2.Channel.Role.DESCRIPTOR.values}
HW_MODEL_NAMES = {v.number: v.name
for v in mesh_pb2.HardwareModel.DESCRIPTOR.values}
# Reverse lookups
REGION_CODES = {v.name: v.number for v in config_pb2.Config.LoRaConfig.RegionCode.DESCRIPTOR.values}
MODEM_PRESETS = {v.name: v.number for v in config_pb2.Config.LoRaConfig.ModemPreset.DESCRIPTOR.values}
DEVICE_ROLES = {v.name: v.number for v in config_pb2.Config.DeviceConfig.Role.DESCRIPTOR.values}
GPS_MODES = {v.name: v.number for v in config_pb2.Config.PositionConfig.GpsMode.DESCRIPTOR.values}
BT_MODES = {v.name: v.number for v in config_pb2.Config.BluetoothConfig.PairingMode.DESCRIPTOR.values}
CHANNEL_ROLES = {v.name: v.number for v in channel_pb2.Channel.Role.DESCRIPTOR.values}
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# PSK HELPERS
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
PUBLIC_PSK = bytes([0x01]) # Meshtastic public mesh shorthand
def derive_channel_psk(name: str, passphrase: str) -> bytes:
"""Derive 32-byte PSK: SHA-256("{name}{passphrase}{name}")."""
return hashlib.sha256(f"{name}{passphrase}{name}".encode()).digest()
def psk_fingerprint(psk: bytes) -> str:
return hashlib.sha256(psk).hexdigest()[:8]
def psk_display(psk: bytes) -> str:
if psk == PUBLIC_PSK:
return "PUBLIC (AQ==)"
if len(psk) == 32:
return f"AES-256 ({psk_fingerprint(psk)})"
if len(psk) == 16:
return f"AES-128 ({psk_fingerprint(psk)})"
if len(psk) == 0:
return "NONE"
return f"{len(psk)}B ({psk_fingerprint(psk)})"
def psk_to_b64(psk: bytes) -> str:
return base64.b64encode(psk).decode()
def psk_from_b64(s: str) -> bytes:
return base64.b64decode(s)
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# ZEROCOMM DEFAULTS
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
ZEROCOMM_DEFAULTS: Dict[str, Any] = {
"region": "US",
"modem_preset": "MEDIUM_FAST",
"tx_power": 20,
"hop_limit": 3,
"tx_enabled": True,
"sx126x_rx_boosted_gain": True,
"ignore_mqtt": True,
"role": "CLIENT",
"node_info_broadcast_secs": 10800,
"gps_mode": "ENABLED",
"gps_update_interval": 60,
"position_broadcast_secs": 3600,
"smart_enabled": True,
"smart_min_secs": 30,
"smart_min_dist": 50,
"position_flags": 769,
"bt_enabled": True,
"bt_mode": "RANDOM_PIN",
}
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# DEVICE STATE β populated from config drain
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@dataclass
class DeviceState:
my_node_num: int = 0
node_id: str = ""
firmware_version: str = ""
hw_model: int = 0
owner_long: str = ""
owner_short: str = ""
config_device: Optional[config_pb2.Config.DeviceConfig] = None
config_position: Optional[config_pb2.Config.PositionConfig] = None
config_power: Optional[config_pb2.Config.PowerConfig] = None
config_network: Optional[config_pb2.Config.NetworkConfig] = None
config_display: Optional[config_pb2.Config.DisplayConfig] = None
config_lora: Optional[config_pb2.Config.LoRaConfig] = None
config_bluetooth: Optional[config_pb2.Config.BluetoothConfig] = None
config_security: Optional[config_pb2.Config.SecurityConfig] = None
channels: List[channel_pb2.Channel] = field(default_factory=list)
connected: bool = False
config_complete: bool = False
def active_channels(self) -> List[channel_pb2.Channel]:
return [ch for ch in self.channels if ch.role != channel_pb2.Channel.DISABLED]
def print_config(self):
section("CURRENT DEVICE CONFIGURATION")
subsection("IDENTITY")
info(f"Node ID: {self.node_id}")
info(f"Long Name: {self.owner_long or '(not set)'}")
info(f"Short Name: {self.owner_short or '(not set)'}")
info(f"Hardware: {HW_MODEL_NAMES.get(self.hw_model, f'Model {self.hw_model}')}")
info(f"Firmware: {self.firmware_version or '(unknown)'}")
subsection("DEVICE")
d = self.config_device
if d:
info(f"Role: {DEVICE_ROLE_NAMES.get(d.role, d.role)}")
info(f"NodeInfo Interval: {d.node_info_broadcast_secs}s")
else:
info("(not received)")
subsection("LORA RADIO")
l = self.config_lora
if l:
info(f"Region: {REGION_NAMES.get(l.region, str(l.region))}")
info(f"Modem Preset: {MODEM_PRESET_NAMES.get(l.modem_preset, str(l.modem_preset))}")
info(f"Use Preset: {l.use_preset}")
info(f"TX Power: {l.tx_power} dBm")
info(f"Hop Limit: {l.hop_limit}")
info(f"TX Enabled: {l.tx_enabled}")
info(f"RX Boosted: {l.sx126x_rx_boosted_gain}")
info(f"Ignore MQTT: {l.ignore_mqtt}")
else:
info("(not received)")
subsection("GPS / POSITION")
p = self.config_position
if p:
info(f"GPS Mode: {GPS_MODE_NAMES.get(p.gps_mode, str(p.gps_mode))}")
info(f"GPS Interval: {p.gps_update_interval}s")
info(f"Broadcast Secs: {p.position_broadcast_secs}s")
info(f"Smart Positioning: {p.position_broadcast_smart_enabled}")
if p.position_broadcast_smart_enabled:
info(f" Min Interval: {p.broadcast_smart_minimum_interval_secs}s")
info(f" Min Distance: {p.broadcast_smart_minimum_distance}m")
else:
info("(not received)")
subsection("BLUETOOTH")
b = self.config_bluetooth
if b:
info(f"Enabled: {b.enabled}")
info(f"Mode: {BT_MODE_NAMES.get(b.mode, str(b.mode))}")
else:
info("(not received)")
subsection("CHANNELS")
active = self.active_channels()
if active:
for ch in active:
role = CHANNEL_ROLE_NAMES.get(ch.role, str(ch.role))
name = ch.settings.name or "(default)"
psk = psk_display(ch.settings.psk)
pp = ch.settings.module_settings.position_precision if ch.settings.HasField("module_settings") else 0
info(f"CH{ch.index} {role:<10} {name:<12} psk={psk:<22} pp={pp}")
else:
info("(no channels configured)")
print()
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# BLE CLIENT
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class MeshtasticBLE:
def __init__(self, address: str):
self.address = address
self.client: Optional[BleakClient] = None
self.state = DeviceState()
self.fromnum_value = 0
self.fromnum_changed = asyncio.Event()
self._config_id = 0
async def connect(self, timeout: float = CONNECT_TIMEOUT) -> bool:
debug_ble(f"Connecting to {self.address}...")
try:
self.client = BleakClient(self.address, timeout=timeout)
await self.client.connect()
debug_ble(f"Connected! MTU = {self.client.mtu_size}")
debug_ble("Enumerating services...")
meshtastic_service = None
for service in self.client.services:
debug_ble(f" Service: {service.uuid}")
for char in service.characteristics:
debug_ble(f" Char: {char.uuid} [{','.join(char.properties)}]")
if service.uuid.lower() == MESHTASTIC_SERVICE_UUID.lower():
meshtastic_service = service
if not meshtastic_service:
err("Meshtastic service not found")
return False
debug_ble(f"Found Meshtastic service")
await self._subscribe_fromnum()
self._config_id = random.randint(1, 0xFFFFFFFF)
await self._request_config(self._config_id)
await self._drain_config(self._config_id)
self.state.connected = True
return True
except Exception as e:
debug_ble(f"Connection failed: {e}")
import traceback; traceback.print_exc()
return False
async def disconnect(self):
if self.client and self.client.is_connected:
debug_ble("Disconnecting...")
try:
await self.client.disconnect()
except Exception as e:
debug_ble(f"Disconnect error (ignored): {e}")
self.state.connected = False
debug_ble("Disconnected")
async def _subscribe_fromnum(self):
debug_ble(f"Subscribing to FROMNUM ({FROMNUM_UUID})...")
def callback(sender, data):
if len(data) >= 4:
new_val = struct.unpack('<I', data[:4])[0]
old_val = self.fromnum_value
self.fromnum_value = new_val
if old_val > 0 and new_val < old_val and self.state.config_complete:
debug_ble(f"β REBOOT DETECTED: FROMNUM {old_val} β {new_val}")
else:
debug_ble(f"FROMNUM notify: {new_val}")
self.fromnum_changed.set()
await self.client.start_notify(FROMNUM_UUID, callback)
debug_ble("FROMNUM notify subscription started")
try:
data = await self.client.read_gatt_char(FROMNUM_UUID)
if data and len(data) >= 4:
self.fromnum_value = struct.unpack('<I', data[:4])[0]
debug_ble(f"Initial FROMNUM: {self.fromnum_value}")
except Exception as e:
debug_ble(f"FROMNUM read error: {e}")
await asyncio.sleep(0.1)
async def _request_config(self, config_id: int):
debug_ble(f"Requesting config (id=0x{config_id:08x})...")
to_radio = mesh_pb2.ToRadio()
to_radio.want_config_id = config_id
msg = to_radio.SerializeToString()
debug_proto(f"ToRadio.want_config_id = {config_id} (0x{config_id:08x})")
debug_proto(f" encoded: {msg.hex()}")
await self.client.write_gatt_char(TORADIO_UUID, msg, response=True)
debug_ble(f"Config request sent ({len(msg)} bytes)")
await asyncio.sleep(0.3)
debug_ble("Waiting for device response...")
try:
await asyncio.wait_for(self.fromnum_changed.wait(), timeout=2.0)
self.fromnum_changed.clear()
except asyncio.TimeoutError:
debug_ble("No FROMNUM notification received, proceeding with drain anyway")
async def _drain_config(self, expected_config_id: int):
debug_drain(f"Starting config drain (expecting id=0x{expected_config_id:08x})...")
print(" Reading device configuration...", end="", flush=True)
start_time = time.time()
msg_count = 0
empty_streak = 0
while True:
elapsed = time.time() - start_time
if elapsed > DRAIN_TIMEOUT:
debug_drain(f"β Drain timeout after {elapsed:.1f}s ({msg_count} messages)")
print(f" timeout ({msg_count} msgs)")
break
try:
data = await self.client.read_gatt_char(FROMRADIO_UUID)
except Exception as e:
debug_drain(f"Read error: {e}")
await asyncio.sleep(0.1)
continue
if not data or len(data) == 0:
empty_streak += 1
if self.state.config_complete and empty_streak >= 3:
print(f" done ({msg_count} msgs)")
break
if msg_count == 0 and empty_streak >= 10:
print(f" no response")
break
if msg_count > 0 and empty_streak >= 3:
print(f" done ({msg_count} msgs)")
break
await asyncio.sleep(0.05)
continue
empty_streak = 0
msg_count += 1
if msg_count % 5 == 0:
print(".", end="", flush=True)
from_radio = mesh_pb2.FromRadio()
try:
from_radio.ParseFromString(data)
except Exception as e:
debug_drain(f"Parse error: {e}")
debug_proto(f" raw hex: {data.hex()}")
continue
variant = from_radio.WhichOneof("payload_variant")
debug_drain(f"FromRadio #{msg_count}: {variant} ({len(data)} bytes)")
if variant == "my_info":
info_ = from_radio.my_info
self.state.my_node_num = info_.my_node_num
self.state.node_id = f"!{info_.my_node_num:08x}"
debug_drain(f" my_node_num = {info_.my_node_num} ({self.state.node_id})")
elif variant == "node_info":
ni = from_radio.node_info
if ni.num == self.state.my_node_num and ni.HasField("user"):
u = ni.user
self.state.owner_long = u.long_name
self.state.owner_short = u.short_name
self.state.hw_model = u.hw_model
debug_drain(f" owner: {u.long_name} ({u.short_name})")
debug_drain(f" hw_model: {HW_MODEL_NAMES.get(u.hw_model, u.hw_model)}")
elif variant == "config":
cfg = from_radio.config
cv = cfg.WhichOneof("payload_variant")
debug_drain(f" Config section: {cv}")
if cv == "device":
self.state.config_device = config_pb2.Config.DeviceConfig(); self.state.config_device.CopyFrom(cfg.device)
elif cv == "position":
self.state.config_position = config_pb2.Config.PositionConfig(); self.state.config_position.CopyFrom(cfg.position)
elif cv == "power":
self.state.config_power = config_pb2.Config.PowerConfig(); self.state.config_power.CopyFrom(cfg.power)
elif cv == "network":
self.state.config_network = config_pb2.Config.NetworkConfig(); self.state.config_network.CopyFrom(cfg.network)
elif cv == "display":
self.state.config_display = config_pb2.Config.DisplayConfig(); self.state.config_display.CopyFrom(cfg.display)
elif cv == "lora":
self.state.config_lora = config_pb2.Config.LoRaConfig(); self.state.config_lora.CopyFrom(cfg.lora)
elif cv == "bluetooth":
self.state.config_bluetooth = config_pb2.Config.BluetoothConfig(); self.state.config_bluetooth.CopyFrom(cfg.bluetooth)
elif cv == "security":
self.state.config_security = config_pb2.Config.SecurityConfig(); self.state.config_security.CopyFrom(cfg.security)
elif variant == "channel":
ch = from_radio.channel
while len(self.state.channels) <= ch.index:
empty_ch = channel_pb2.Channel()
empty_ch.index = len(self.state.channels)
self.state.channels.append(empty_ch)
self.state.channels[ch.index].CopyFrom(ch)
rn = CHANNEL_ROLE_NAMES.get(ch.role, str(ch.role))
debug_drain(f" Channel[{ch.index}]: {ch.settings.name or '(default)'} role={rn}")
elif variant == "moduleConfig":
mc = from_radio.moduleConfig
debug_drain(f" ModuleConfig: {mc.WhichOneof('payload_variant')}")
elif variant == "config_complete_id":
cid = from_radio.config_complete_id
if cid == expected_config_id:
debug_drain(f"β Config complete! ({msg_count} messages in {elapsed:.1f}s)")
self.state.config_complete = True
else:
debug_drain(f"β Unexpected config_complete_id: 0x{cid:08x}")
elif variant == "metadata":
md = from_radio.metadata
self.state.firmware_version = md.firmware_version
debug_drain(f" firmware: {md.firmware_version}")
elif variant == "packet":
debug_drain(f" MeshPacket (id=0x{from_radio.packet.id:08x})")
elif variant:
debug_drain(f" (skipping {variant})")
await asyncio.sleep(0.01)
async def write_admin(self, admin_msg: admin_pb2.AdminMessage,
expect_reboot: bool = False) -> bool:
if not self.client or not self.client.is_connected:
debug_admin("ERROR: Not connected")
return False
data = mesh_pb2.Data()
data.portnum = portnums_pb2.ADMIN_APP
data.payload = admin_msg.SerializeToString()
mesh_packet = mesh_pb2.MeshPacket()
mesh_packet.to = self.state.my_node_num
mesh_packet.id = random.randint(1, 0xFFFFFFFF)
mesh_packet.hop_limit = 3
mesh_packet.decoded.CopyFrom(data)
to_radio = mesh_pb2.ToRadio()
to_radio.packet.CopyFrom(mesh_packet)
payload = to_radio.SerializeToString()
debug_admin(f"Sending admin message ({len(payload)} bytes)...")
debug_proto(f" hex: {payload.hex()[:80]}...")
try:
await self.client.write_gatt_char(TORADIO_UUID, payload, response=True)
debug_admin("β Write complete")
if expect_reboot:
await asyncio.sleep(POST_WRITE_DELAY)
return True
except Exception as e:
debug_admin(f"Write error: {e}")
return False
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# ADMIN MESSAGE BUILDERS
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def build_set_owner(long_name: str, short_name: str,
is_licensed: bool = False) -> admin_pb2.AdminMessage:
admin = admin_pb2.AdminMessage()
admin.set_owner.long_name = long_name
admin.set_owner.short_name = short_name[:4]
admin.set_owner.is_licensed = is_licensed
debug_admin(f"set_owner: long='{long_name}' short='{short_name[:4]}'")
return admin
def build_set_channel(index: int, name: str, psk: bytes,
role: int, position_precision: int = 0) -> admin_pb2.AdminMessage:
admin = admin_pb2.AdminMessage()
ch = admin.set_channel
ch.index = index
ch.role = role
ch.settings.psk = psk
if name:
ch.settings.name = name
if position_precision > 0:
ch.settings.module_settings.position_precision = position_precision
debug_admin(f"set_channel[{index}]: name='{name}' role={CHANNEL_ROLE_NAMES.get(role, role)} psk={psk_display(psk)}")
return admin
def build_set_config_lora(region: int, modem_preset: int, tx_power: int,
hop_limit: int, tx_enabled: bool = True,
use_preset: bool = True,
sx126x_rx_boosted_gain: bool = True,
ignore_mqtt: bool = True) -> admin_pb2.AdminMessage:
admin = admin_pb2.AdminMessage()
lora = admin.set_config.lora
lora.use_preset = use_preset
lora.modem_preset = modem_preset
lora.region = region
lora.hop_limit = hop_limit
lora.tx_enabled = tx_enabled
lora.tx_power = tx_power
lora.sx126x_rx_boosted_gain = sx126x_rx_boosted_gain
lora.ignore_mqtt = ignore_mqtt
debug_admin(f"set_config(lora): region={REGION_NAMES.get(region, region)} "
f"preset={MODEM_PRESET_NAMES.get(modem_preset, modem_preset)} "
f"tx={tx_power}dBm hops={hop_limit}")
return admin
def build_set_config_device(role: int,
node_info_broadcast_secs: int = 10800) -> admin_pb2.AdminMessage:
admin = admin_pb2.AdminMessage()
dev = admin.set_config.device
dev.role = role
dev.node_info_broadcast_secs = node_info_broadcast_secs
debug_admin(f"set_config(device): role={DEVICE_ROLE_NAMES.get(role, role)} "
f"nodeinfo={node_info_broadcast_secs}s")
return admin
def build_set_config_position(gps_mode: int, gps_update_interval: int = 60,
position_broadcast_secs: int = 3600,
smart_enabled: bool = True,
smart_min_secs: int = 30,
smart_min_dist: int = 50,
position_flags: int = 769) -> admin_pb2.AdminMessage:
admin = admin_pb2.AdminMessage()
pos = admin.set_config.position
pos.gps_mode = gps_mode
pos.gps_update_interval = gps_update_interval
pos.position_broadcast_secs = position_broadcast_secs
pos.position_broadcast_smart_enabled = smart_enabled
pos.broadcast_smart_minimum_interval_secs = smart_min_secs
pos.broadcast_smart_minimum_distance = smart_min_dist
pos.position_flags = position_flags
debug_admin(f"set_config(position): gps={GPS_MODE_NAMES.get(gps_mode, gps_mode)} "
f"interval={gps_update_interval}s broadcast={position_broadcast_secs}s")
return admin
def build_set_config_bluetooth(enabled: bool = True, mode: int = 0) -> admin_pb2.AdminMessage:
admin = admin_pb2.AdminMessage()
bt = admin.set_config.bluetooth
bt.enabled = enabled
bt.mode = mode
debug_admin(f"set_config(bluetooth): enabled={enabled} mode={BT_MODE_NAMES.get(mode, mode)}")
return admin
def build_set_config_security(public_key: bytes, private_key: bytes,
admin_key: bytes = b"") -> admin_pb2.AdminMessage:
admin = admin_pb2.AdminMessage()
sec = admin.set_config.security
sec.public_key = public_key
sec.private_key = private_key
if admin_key:
sec.admin_key = admin_key
debug_admin(f"set_config(security): pub={public_key.hex()[:16]}... "
f"priv=<{len(private_key)}B redacted>")
return admin
def build_factory_reset(full: bool = False) -> admin_pb2.AdminMessage:
admin = admin_pb2.AdminMessage()
if full:
admin.factory_reset_device = 1
debug_admin("factory_reset_device = 1 (FULL WIPE including BLE keys)")
else:
admin.factory_reset_config = 1
debug_admin("factory_reset_config = 1 (config only, preserves keys)")
return admin
def build_reboot(seconds: int = 3) -> admin_pb2.AdminMessage:
admin = admin_pb2.AdminMessage()
admin.reboot_seconds = seconds
debug_admin(f"reboot_seconds = {seconds}")
return admin
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# CONFIG FILE β SAVE / LOAD (human + machine readable JSON)
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def state_to_config_dict(state: DeviceState, include_keys: bool = False) -> Dict[str, Any]:
"""Serialize DeviceState to a plain dict suitable for JSON."""
d: Dict[str, Any] = {
"_meta": {
"tool": "meshtastic_admin",
"version": "2",
"saved": datetime.now().isoformat(),
"node_id": state.node_id,
"include_keys": include_keys,
},
"identity": {
"node_id": state.node_id,
"long_name": state.owner_long,
"short_name": state.owner_short,
"hw_model": HW_MODEL_NAMES.get(state.hw_model, str(state.hw_model)),
"firmware_version": state.firmware_version,
},
}
if state.config_lora:
l = state.config_lora
d["lora"] = {
"region": REGION_NAMES.get(l.region, str(l.region)),
"modem_preset": MODEM_PRESET_NAMES.get(l.modem_preset, str(l.modem_preset)),
"use_preset": l.use_preset,
"tx_power": l.tx_power,
"hop_limit": l.hop_limit,
"tx_enabled": l.tx_enabled,
"sx126x_rx_boosted_gain": l.sx126x_rx_boosted_gain,
"ignore_mqtt": l.ignore_mqtt,
}
if state.config_device:
dv = state.config_device
d["device"] = {
"role": DEVICE_ROLE_NAMES.get(dv.role, str(dv.role)),
"node_info_broadcast_secs": dv.node_info_broadcast_secs,
}
if state.config_position:
p = state.config_position
d["position"] = {
"gps_mode": GPS_MODE_NAMES.get(p.gps_mode, str(p.gps_mode)),
"gps_update_interval": p.gps_update_interval,
"position_broadcast_secs": p.position_broadcast_secs,
"position_broadcast_smart_enabled": p.position_broadcast_smart_enabled,
"broadcast_smart_minimum_interval_secs": p.broadcast_smart_minimum_interval_secs,
"broadcast_smart_minimum_distance": p.broadcast_smart_minimum_distance,
"position_flags": p.position_flags,
}
if state.config_bluetooth:
b = state.config_bluetooth
d["bluetooth"] = {
"enabled": b.enabled,
"mode": BT_MODE_NAMES.get(b.mode, str(b.mode)),
}
# Channels β include PSK as base64
ch_list = []
for ch in state.active_channels():
pp = ch.settings.module_settings.position_precision if ch.settings.HasField("module_settings") else 0
ch_list.append({
"index": ch.index,
"name": ch.settings.name,
"role": CHANNEL_ROLE_NAMES.get(ch.role, str(ch.role)),
"psk_b64": psk_to_b64(ch.settings.psk),
"psk_display": psk_display(ch.settings.psk),
"position_precision": pp,
})
d["channels"] = ch_list
# Keys β only if explicitly requested
if include_keys and state.config_security:
sec = state.config_security
d["security"] = {
"_warning": "PRIVATE KEY β keep this file secure",
"public_key_b64": base64.b64encode(sec.public_key).decode() if sec.public_key else "",
"private_key_b64": base64.b64encode(sec.private_key).decode() if sec.private_key else "",
"admin_key_b64": base64.b64encode(sec.admin_key).decode() if sec.admin_key else "",
}
return d
def save_config_file(state: DeviceState, include_keys: bool = False) -> str:
"""Write config to JSON file. Returns filename."""
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
name = state.owner_long.replace(" ", "_") or state.node_id.replace("!", "")
suffix = "_keys" if include_keys else "_config"
fname = f"{name}{suffix}_{ts}.json"
d = state_to_config_dict(state, include_keys=include_keys)
with open(fname, "w") as f:
json.dump(d, f, indent=2)
return fname
def load_config_file(path: str) -> Dict[str, Any]:
"""Load and validate a config JSON file."""
with open(path) as f:
d = json.load(f)
if "_meta" not in d:
raise ValueError("Not a valid meshtastic_admin config file (missing _meta)")
return d
def pick_file(label: str = "Select file", keys_only: bool = False) -> Optional[str]:
"""
Interactive file browser.
Lists .json files in current dir (and optionally another dir).
Returns selected path or None if cancelled.
"""
def _list_json(directory: str) -> List[str]:
try:
files = sorted(
f for f in os.listdir(directory)
if f.endswith(".json")
and (not keys_only or "_keys_" in f)
)
return files
except PermissionError:
return []
current_dir = os.getcwd()
while True:
files = _list_json(current_dir)
print(f"\n {label}")
print(f" Directory: {current_dir}")
print()
if not files:
print(" (no .json files here)")
else:
for i, fname in enumerate(files, 1):
fpath = os.path.join(current_dir, fname)
try:
sz = os.path.getsize(fpath)
mtime = datetime.fromtimestamp(os.path.getmtime(fpath)).strftime("%Y-%m-%d %H:%M")
except OSError:
sz, mtime = 0, "?"
# Try to peek at node_id + saved from _meta
tag = ""
try:
with open(fpath) as f:
peek = json.load(f)
meta = peek.get("_meta", {})
node = meta.get("node_id", "")
saved = meta.get("saved", "")[:16]
has_keys = "π" if meta.get("include_keys") else ""
tag = f" {node} {saved} {has_keys}".rstrip()
except Exception:
pass
print(f" {i:>2}) {fname:<50} {sz:>6}B {mtime}{tag}")
print()
print(" Enter number, path, or 'd <path>' to change directory (q=cancel)")
raw = input(" > ").strip()
if not raw or raw.lower() == "q":
return None
if raw.lower().startswith("d "):
new_dir = raw[2:].strip().rstrip("/") or "/"
new_dir = os.path.expanduser(new_dir)
if os.path.isdir(new_dir):
current_dir = os.path.abspath(new_dir)
else:
warn(f"Not a directory: {new_dir}")
continue
# Numeric selection
try:
idx = int(raw) - 1
if 0 <= idx < len(files):
return os.path.join(current_dir, files[idx])
else:
warn("Number out of range")
continue
except ValueError:
pass
# Direct path
path = os.path.expanduser(raw)
if os.path.isfile(path):
return path
# Maybe they typed a bare filename in current dir
candidate = os.path.join(current_dir, path)
if os.path.isfile(candidate):
return candidate
warn(f"File not found: {raw}")
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# BLE SCAN
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
async def scan_for_devices(timeout: float = SCAN_TIMEOUT) -> List[tuple]:
info(f"Scanning for Meshtastic devices ({timeout}s)...")
devices = []
seen = set()
def detection_callback(device, advertisement_data):
if device.address in seen: return
seen.add(device.address)
name = device.name or advertisement_data.local_name or "Unknown"
rssi = advertisement_data.rssi if advertisement_data.rssi else -999
service_uuids = advertisement_data.service_uuids or []
is_meshtastic = any(MESHTASTIC_SERVICE_UUID.lower() in u.lower() for u in service_uuids)
if is_meshtastic or ("_" in name and len(name) >= 4):
devices.append((device.address, name, rssi))
debug_ble(f"Found: {name} ({device.address}) RSSI={rssi}")
try:
scanner = BleakScanner(detection_callback=detection_callback,
service_uuids=[MESHTASTIC_SERVICE_UUID])
await scanner.start()
await asyncio.sleep(timeout)
await scanner.stop()
except Exception:
seen.clear(); devices.clear()
scanner = BleakScanner(detection_callback=detection_callback)
await scanner.start()
await asyncio.sleep(timeout)
await scanner.stop()
devices.sort(key=lambda x: x[2], reverse=True)
return devices
def rssi_bar(rssi: int) -> str:
bars = 5 if rssi >= -50 else 4 if rssi >= -60 else 3 if rssi >= -70 else 2 if rssi >= -80 else 1
return "β" * bars + "β" * (5 - bars)
async def pick_device() -> Optional[str]:
devices = await scan_for_devices()
if not devices:
err("No devices found.")
return None
print(f"\n Found {len(devices)} device(s):\n")
for i, (addr, name, rssi) in enumerate(devices, 1):
print(f" {i}) {name:<20} {addr} {rssi:>4} dBm {rssi_bar(rssi)}")
print()
if len(devices) == 1:
if input(" Connect? [Y/n]: ").strip().lower() in ("n", "no"):
return None
return devices[0][0]
sel = input(f" Select [1-{len(devices)}]: ").strip()
try:
idx = int(sel) - 1
if 0 <= idx < len(devices):
return devices[idx][0]
except ValueError:
pass
err("Invalid selection")
return None
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# VERIFICATION β reconnect and compare
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
async def reconnect_and_verify(ble: MeshtasticBLE, reboot_wait: bool = False) -> bool:
"""Disconnect, optionally wait for reboot, reconnect, drain, return success."""
debug_ble("Disconnecting before verify reconnect...")
await ble.disconnect()
if reboot_wait:
info(f"Waiting {REBOOT_WAIT}s for device reboot...")
await asyncio.sleep(REBOOT_WAIT)
info(f"Waiting {RECONNECT_DELAY}s before reconnect...")
await asyncio.sleep(RECONNECT_DELAY)
info("Reconnecting for verification...")
ble.state = DeviceState() # reset state β fresh drain
ble.fromnum_value = 0
ble.fromnum_changed.clear()
if not await ble.connect():
err("Reconnect failed")
return False
ok("Reconnected and drained successfully")
return True
def verify_owner(state: DeviceState, expected_long: str, expected_short: str) -> bool:
ok_ = True
info(f"[verify owner] long_name: {state.owner_long!r} (expected {expected_long!r})")
if state.owner_long != expected_long:
warn(f" MISMATCH: long_name"); ok_ = False
info(f"[verify owner] short_name: {state.owner_short!r} (expected {expected_short!r})")
if state.owner_short != expected_short:
warn(f" MISMATCH: short_name"); ok_ = False
return ok_
def verify_channels(state: DeviceState, expected: List[Dict]) -> bool:
ok_ = True
for exp in expected:
idx = exp["index"]
matches = [ch for ch in state.channels if ch.index == idx]
if not matches:
warn(f" CH{idx}: not found in drain"); ok_ = False; continue
ch = matches[0]
info(f"[verify CH{idx}] name={ch.settings.name!r} role={CHANNEL_ROLE_NAMES.get(ch.role,'?')} "
f"psk={psk_display(ch.settings.psk)}")
if ch.settings.name != exp.get("name", ""):
warn(f" CH{idx}: name MISMATCH (got {ch.settings.name!r}, expected {exp['name']!r})"); ok_ = False
exp_psk = exp.get("psk", b"")
if ch.settings.psk != exp_psk:
warn(f" CH{idx}: PSK MISMATCH"); ok_ = False
exp_role = exp.get("role", channel_pb2.Channel.DISABLED)
if ch.role != exp_role:
warn(f" CH{idx}: role MISMATCH"); ok_ = False
return ok_
def verify_lora(state: DeviceState, region: int, modem_preset: int,
tx_power: int, hop_limit: int) -> bool:
l = state.config_lora
if not l: