-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmesh_interface.py
More file actions
858 lines (718 loc) · 33.5 KB
/
Copy pathmesh_interface.py
File metadata and controls
858 lines (718 loc) · 33.5 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
"""
MeshCore Python library wrapper for LoRa mesh communication.
Handles sending and receiving messages via meshcore_py with rate limiting
to prevent network flooding. Designed for Heltec V3 LoRa radio.
"""
import asyncio
import time
import re
import unicodedata
import os
import glob
from queue import Queue
from typing import Optional, Tuple, Dict, List
from datetime import datetime, timedelta
try:
from meshcore import MeshCore, EventType
except ImportError:
raise ImportError(
"meshcore package not found. Please install it:\n"
" pip install meshcore\n"
"Or:\n"
" pipx install meshcore-cli"
)
import config
def _normalize_text(value: str) -> str:
"""
Normalize text for robust matching.
Handles odd spacing (including NBSP), so collapse all
whitespace to single spaces and trim.
"""
if value is None:
return ""
# Normalize a wide set of unicode whitespace / zero-width chars
value = str(value)
value = value.replace("\ufeff", "") # BOM / zero-width no-break space
value = value.replace("\u200b", "") # zero-width space
value = value.replace("\u200c", "") # zero-width non-joiner
value = value.replace("\u200d", "") # zero-width joiner
# Convert any whitespace to normal spaces so collapse works consistently.
value = "".join((" " if ch.isspace() else ch) for ch in value)
return re.sub(r"[ ]+", " ", value).strip()
def _normalize_contact_name(value: str) -> str:
"""
Normalize a MeshCore contact name into a stable lookup key.
CRITICAL: This function MUST preserve the actual name and only remove invisible/format characters.
It should NOT remove visible characters that are part of the name.
"""
if not value:
return ""
# First normalize whitespace (this handles NBSP and other whitespace issues)
text = _normalize_text(value)
if not text:
return ""
# Remove all control/format characters (Cc/Cf) defensively - these are invisible
# but preserve all visible characters including alphanumeric, underscore, dot, dash
cleaned = []
for ch in text:
cat = unicodedata.category(ch)
# Keep printable characters (letters, numbers, punctuation like dash, dot, underscore)
if cat[0] in ('L', 'N', 'P', 'S'): # Letter, Number, Punctuation, Symbol
cleaned.append(ch)
elif cat in ('Cc', 'Cf'): # Control and Format characters - skip these
continue
# For any other category, be conservative and keep it
else:
cleaned.append(ch)
text = "".join(cleaned)
# Keep only characters we expect in mesh names (alnum + _ . -).
normalized = re.sub(r"[^A-Za-z0-9_.-]+", "", text)
return normalized
def _is_running_as_root() -> bool:
"""Check if the current process is running as root."""
try:
return os.geteuid() == 0
except AttributeError:
# Windows or other platform without geteuid
return False
def _discover_serial_ports() -> List[str]:
"""
Discover available serial ports (ttyUSB devices).
Returns:
List of serial port paths (e.g., ['/dev/ttyUSB0', '/dev/ttyUSB1'])
"""
ports = []
# Common serial port patterns
patterns = [
'/dev/ttyUSB*', # USB serial adapters
'/dev/ttyACM*', # USB CDC devices
'/dev/ttyS*', # Serial ports
]
for pattern in patterns:
try:
found_ports = glob.glob(pattern)
for port in found_ports:
# Check if port is accessible
if os.path.exists(port):
ports.append(port)
except Exception:
pass
# Sort ports naturally (ttyUSB0 before ttyUSB10)
def sort_key(port):
parts = port.split('/')[-1]
prefix = ''.join(c for c in parts if not c.isdigit())
number = int(re.search(r'\d+', parts).group()) if re.search(r'\d+', parts) else 0
return (prefix, number)
ports.sort(key=sort_key)
return ports
class MeshHandler:
"""
Handles all MeshCore communication using meshcore_py library.
Hardware: Heltec V3 LoRa radio running latest MeshCore firmware,
connected to Raspberry Pi via USB serial (ttyUSB).
"""
def __init__(self, min_send_interval: float = 2.0, max_message_length: int = 200):
"""
Initialize MeshHandler.
Args:
min_send_interval: Minimum seconds between sends (default: 2.0)
max_message_length: Maximum message length in bytes (default: 200)
"""
self.meshcore: Optional[MeshCore] = None
self.message_queue = Queue()
self.last_send_time = None
self.min_send_interval = min_send_interval
self.max_message_length = max_message_length
self.radio_version = None
self.radio_info = None
# Serial connection info
self.serial_port = None
self.friends = set() # Track discovered nodes as friends
# Cache for contacts mapping (adv_name -> public_key)
self._contacts_cache_ts = 0.0
self._contacts_cache_ttl_s = 10.0
self._contacts_cache_name_to_pubkey: Dict[str, str] = {}
# Message event handler
self._pending_messages: List[Tuple[str, str]] = []
async def initialize(self):
"""Initialize and connect to serial device (async)."""
await self._connect_serial()
async def _connect_serial(self):
"""
Establish serial connection to MeshCore radio using meshcore_py.
Flow:
1. Check database for stored serial port
2. If stored port exists, try to connect directly
3. If not found or connection fails, auto-detect or prompt for port
4. Connect using MeshCore.create_serial()
5. Store successful connection
"""
import database
import glob
# Step 1: Check database for stored serial port
stored_port = database.get_stored_serial_port()
if stored_port:
print(f"Found stored serial port: {stored_port}")
print("Attempting to connect...")
# Try to connect directly with stored port
try:
self.meshcore = await MeshCore.create_serial(stored_port)
if self.meshcore:
self.serial_port = stored_port
database.update_serial_port_connection(stored_port)
print(f"Connected to serial port: {stored_port}")
# Test connection by getting device info
try:
info_result = await self.meshcore.commands.send_device_query()
if info_result and info_result.type == EventType.ERROR:
raise RuntimeError(f"Connection test failed: {info_result.payload}")
except Exception as e:
print(f"Warning: Could not verify connection: {e}")
return
except Exception as e:
print(f"Failed to connect to stored port: {e}")
self.meshcore = None
# Step 2: Auto-detect ttyUSB devices
print("Scanning for serial devices...")
serial_ports = _discover_serial_ports()
selected_port = None
if serial_ports:
if len(serial_ports) == 1:
# Only one port found, use it automatically
selected_port = serial_ports[0]
print(f"Auto-selected serial port: {selected_port}")
else:
# Multiple ports found, let user choose
print("\nAvailable serial ports:")
for i, port in enumerate(serial_ports, 1):
print(f" {i}. {port}")
try:
choice = input(f"Select port (1-{len(serial_ports)}) or press Enter for {serial_ports[0]}: ").strip()
if not choice:
selected_port = serial_ports[0]
else:
index = int(choice) - 1
if 0 <= index < len(serial_ports):
selected_port = serial_ports[index]
else:
raise ValueError("Invalid selection")
except (ValueError, KeyboardInterrupt):
raise RuntimeError("No serial port selected")
if not selected_port:
# Fallback: Allow manual port entry
print("\nNo serial port detected. You can enter port manually.")
print("Common ports: /dev/ttyUSB0, /dev/ttyUSB1, /dev/ttyACM0")
port_input = input("Enter serial port (or press Enter to cancel): ").strip()
if not port_input:
raise RuntimeError("No serial port specified")
# Validate port format
if not port_input.startswith('/dev/'):
port_input = f'/dev/{port_input}'
if not os.path.exists(port_input):
raise RuntimeError(f"Serial port does not exist: {port_input}")
selected_port = port_input
# Step 3: Connect using meshcore_py
print(f"Connecting to serial port: {selected_port}...")
try:
self.meshcore = await MeshCore.create_serial(selected_port)
if not self.meshcore:
raise RuntimeError("Failed to create MeshCore connection")
# Test connection by getting device info
try:
info_result = await self.meshcore.commands.send_device_query()
if info_result and info_result.type == EventType.ERROR:
raise RuntimeError(f"Connection test failed: {info_result.payload}")
except Exception as e:
print(f"Warning: Could not verify connection: {e}")
# Store successful connection
self.serial_port = selected_port
database.store_serial_port(selected_port)
database.update_serial_port_connection(selected_port)
print(f"Successfully connected to serial port: {selected_port}")
except PermissionError:
print(f"Permission denied accessing {selected_port}")
print("Please ensure you are in the 'dialout' group:")
print(" sudo usermod -a -G dialout $USER")
print(" (Then log out and log back in)")
raise RuntimeError(f"Permission denied: {selected_port}")
except FileNotFoundError:
print(f"Serial port not found: {selected_port}")
raise RuntimeError(f"Serial port not found: {selected_port}")
except Exception as e:
print(f"Failed to connect: {e}")
print("Please check:")
print(" - Device is powered on and connected")
print(" - Serial port is correct")
print(" - You have permission to access the port (dialout group)")
print(" - No other program is using the port")
raise RuntimeError(f"Failed to connect to serial port {selected_port}")
async def listen(self) -> Optional[Tuple[str, str]]:
"""
Poll for new messages using meshcore_py get_msg().
Returns:
Tuple of (sender_node_id, message_text) or None if no message
"""
if not self.meshcore:
return None
try:
# Use meshcore_py get_msg with short timeout
result = await self.meshcore.commands.get_msg(timeout=2.0)
if not result:
return None
if result.type == EventType.CONTACT_MSG_RECV:
payload = result.payload
node_id = payload.get("pubkey_prefix") or payload.get("pubkey")
message = payload.get("text")
if node_id and message:
# Clean node_id (remove ! prefix, ensure lowercase)
node_id = node_id.lstrip("!").lower().strip()
# Verify it's a valid hex string
if re.fullmatch(r'^[a-f0-9]{8,}$', node_id):
# Store node ID in friends
if node_id not in self.friends:
self.friends.add(node_id)
return (node_id, message)
elif result.type == EventType.CHANNEL_MSG_RECV:
# Handle channel messages if needed
payload = result.payload
node_id = payload.get("pubkey_prefix") or payload.get("pubkey")
message = payload.get("text")
if node_id and message:
node_id = node_id.lstrip("!").lower().strip()
if re.fullmatch(r'^[a-f0-9]{8,}$', node_id):
if node_id not in self.friends:
self.friends.add(node_id)
return (node_id, message)
return None
except Exception as e:
# Log error but don't crash
print(f"[ERROR] Error listening for messages: {e}")
return None
def send(self, node_id: str, text: str):
"""
Queue message for sending with rate limiting.
This is a synchronous method that queues messages.
The queue is processed asynchronously by process_pending_messages().
Args:
node_id: Target Node ID (hex string, e.g., "a1b2c3d4e5f6")
text: Message text to send
"""
# Strip whitespace from node_id
node_id = node_id.strip().lstrip("!")
# Verify node_id is a valid hex string
if not re.fullmatch(r'^[a-fA-F0-9]{8,}$', node_id):
# For name lookup, we'll need to do it async later
# For now, just queue it and let async processing handle the lookup
pass
# Sanitize message
sanitized = self._sanitize_message(text)
# Add to queue (with original node_id - async processing will validate/lookup)
self.message_queue.put((node_id, sanitized))
async def _process_queue(self):
"""Internal method to send queued messages respecting rate limits."""
if self.message_queue.empty() or not self.meshcore:
return
# Check if enough time has passed
now = datetime.now()
if self.last_send_time is not None:
time_since_last = (now - self.last_send_time).total_seconds()
if time_since_last < self.min_send_interval:
return
# Send next message from queue
try:
node_id, message = self.message_queue.get_nowait()
node_id = node_id.strip().lstrip("!")
# If node_id is not a hex string, try to look it up
if not re.fullmatch(r'^[a-fA-F0-9]{8,}$', node_id):
# Get contacts mapping
name_to_pub = await self._get_contacts_name_to_pubkey_map()
# Try exact match
node_id_actual = name_to_pub.get(node_id)
if not node_id_actual:
# Try normalized name
normalized_name = _normalize_contact_name(node_id)
node_id_actual = name_to_pub.get(normalized_name)
if not node_id_actual:
# Try case-insensitive match
for name, pub in name_to_pub.items():
if name.lower() == node_id.lower():
node_id_actual = pub
break
if node_id_actual and re.fullmatch(r'^[a-fA-F0-9]{8,}$', node_id_actual):
node_id = node_id_actual
else:
# Can't resolve node_id, skip this message
return
# Final verification
if not re.fullmatch(r'^[a-fA-F0-9]{8,}$', node_id):
return
# Ensure contact is added (meshcore handles this automatically, but we can try)
await self._ensure_contact(node_id)
# Send via meshcore_py
result = await self.meshcore.commands.send_msg(node_id, message)
if result:
if result.type == EventType.MSG_SENT:
self.last_send_time = now
elif result.type == EventType.ERROR:
print(f"Failed to send message: {result.payload}")
except Exception as e:
print(f"Error processing message queue: {e}")
async def process_pending_messages(self):
"""Process any pending messages in the queue."""
await self._process_queue()
async def _get_contacts_name_to_pubkey_map(self, force_refresh: bool = False) -> Dict[str, str]:
"""
Get contacts mapping (name -> hex node ID) using meshcore_py.
Returns:
Dictionary mapping contact names to hex node IDs
"""
if not self.meshcore:
return {}
now = time.time()
if not force_refresh and (now - self._contacts_cache_ts) < self._contacts_cache_ttl_s:
return self._contacts_cache_name_to_pubkey
try:
result = await self.meshcore.commands.get_contacts()
if not result:
return {}
if result.type == EventType.ERROR:
return {}
contacts = result.payload
if not isinstance(contacts, dict):
return {}
mapping: Dict[str, str] = {}
for public_key, info in contacts.items():
if not isinstance(public_key, str) or not isinstance(info, dict):
continue
adv_name = info.get("adv_name") or info.get("name")
if not isinstance(adv_name, str) or not adv_name.strip():
continue
name_clean = adv_name.strip()
pub_norm = public_key.lstrip("!").lower().strip()
if not re.fullmatch(r"[a-f0-9]{8,}", pub_norm):
continue
# Use short hex ID
dest = pub_norm[:12] if len(pub_norm) >= 12 else pub_norm
mapping[name_clean] = dest
# Cache
self._contacts_cache_ts = now
self._contacts_cache_name_to_pubkey = mapping
# Store in DB for persistence
if mapping:
try:
import database
for n, k in mapping.items():
database.store_contact(n, k)
except Exception:
pass
return mapping
except Exception as e:
return {}
async def _ensure_contact(self, node_id: str) -> bool:
"""Ensure a contact is added using meshcore_py."""
if not self.meshcore:
return False
try:
# add_contact expects a contact dict, not just node_id
# Format: {"public_key": node_id, ...}
# For now, contacts are usually auto-added from adverts
# So we'll just return True - meshcore handles this automatically
return True
except Exception:
return True
def _sanitize_message(self, text: str) -> str:
"""Sanitize message text for transmission."""
if not text:
return ""
lines = text.split('\n')
is_ascii_art = False
# Detect ASCII art - look for patterns that indicate ASCII art
# ASCII art typically has multiple lines with special characters
ascii_art_chars = set('|/\\-+*#@$%&()[]{}<>')
ascii_line_count = 0
for line in lines:
if any(c in ascii_art_chars for c in line):
ascii_line_count += 1
# More strict detection: need at least 2 lines with ASCII art chars
# and at least 50% of lines should have ASCII art chars
if len(lines) >= 2 and ascii_line_count >= max(2, len(lines) * 0.5):
is_ascii_art = True
if is_ascii_art:
# For ASCII art, preserve it exactly as-is (it's already validated to be under 198 chars)
# Only ensure it's under max_message_length
sanitized = text
else:
# For regular text, clean up whitespace
cleaned_lines = [line.rstrip() for line in lines]
while cleaned_lines and not cleaned_lines[0].strip():
cleaned_lines.pop(0)
while cleaned_lines and not cleaned_lines[-1].strip():
cleaned_lines.pop()
sanitized = '\n'.join(cleaned_lines)
# Ensure under max length (safety check)
if len(sanitized.encode('utf-8')) > self.max_message_length:
# Truncate carefully to preserve structure
byte_len = len(sanitized.encode('utf-8'))
if is_ascii_art:
# For ASCII art, try to preserve complete lines
lines = sanitized.split('\n')
result_lines = []
current_bytes = 0
for line in lines:
line_bytes = len(line.encode('utf-8')) + 1 # +1 for newline
if current_bytes + line_bytes <= self.max_message_length - 3:
result_lines.append(line)
current_bytes += line_bytes
else:
break
sanitized = '\n'.join(result_lines)
if len(sanitized.encode('utf-8')) < self.max_message_length - 3:
sanitized += "..."
else:
# For regular text, truncate character by character
while len(sanitized.encode('utf-8')) > self.max_message_length:
sanitized = sanitized[:-1]
if len(sanitized.encode('utf-8')) < self.max_message_length - 3:
sanitized += "..."
return sanitized
async def initialize_radio(self) -> bool:
"""
Initialize and configure radio at startup.
Ensures:
1. Radio is configured using settings from config.ini
2. Radio name is set from config.ini
3. Radio performs flood and zero-hop advert
4. Message relay (repeat) is set to on
Returns:
True if successful, False otherwise
"""
try:
print("Initializing radio configuration...")
# Get radio version
version_info = await self.get_radio_version()
if version_info:
self.radio_version = version_info
print(f"Radio version: {version_info}")
# Get radio link information
link_info = await self.get_radio_link_info()
if link_info:
self.radio_info = link_info
# Step 1: Configure radio from config.ini
print("\n[1/3] Configuring radio from config.ini...")
preset_success = await self.configure_radio_preset()
# Step 2: Set radio name from config.ini
cfg = config.get_config()
radio_name = cfg.get_radio_name()
print("\n[2/3] Setting radio name...")
name_success = await self.set_radio_name(radio_name)
# Step 3: Send initial flood and zero-hop adverts
print("\n[3/3] Sending flood and zero-hop adverts...")
await self.send_flood_advert(count=5, delay=0.5)
await self.send_zero_hop_advert(count=5, delay=0.5)
# Step 4: Set message relay (repeat) to on so node forwards packets
print("\n[4/4] Setting message relay to on...")
await self.set_message_relay(True)
# Consider initialization successful if at least preset or name worked
# (Some operations might not be available in all firmware versions)
if preset_success or name_success:
print("\nRadio initialization complete")
return True
else:
print("\nWarning: Radio initialization had issues, but continuing...")
return True # Don't block startup
except Exception as e:
print(f"Error initializing radio: {e}")
import traceback
traceback.print_exc()
# Don't block startup on radio init errors
return True
async def set_message_relay(self, enabled: bool) -> bool:
"""Set message relay (packet forwarding / repeat) on or off. Uses custom var 'repeat'."""
if not self.meshcore:
return False
try:
value = "on" if enabled else "off"
result = await self.meshcore.commands.set_custom_var("repeat", value)
if result and result.type == EventType.ERROR:
print(f"Warning: Could not set message relay: {result.payload}")
return False
return True
except Exception as e:
print(f"Warning: set_message_relay failed: {e}")
return False
async def get_radio_version(self) -> Optional[str]:
"""Get radio firmware version using meshcore_py."""
if not self.meshcore:
return None
try:
result = await self.meshcore.commands.send_device_query()
if result and result.type == EventType.DEVICE_INFO:
info = result.payload
if isinstance(info, dict):
return info.get("version") or info.get("ver") or info.get("firmware_version")
return None
except Exception:
return None
async def get_radio_link_info(self) -> Optional[Dict]:
"""Get radio link information using meshcore_py."""
if not self.meshcore:
return None
try:
result = await self.meshcore.commands.send_device_query()
if result and result.type == EventType.DEVICE_INFO:
info = result.payload
if isinstance(info, dict):
return info
return None
except Exception:
return None
async def configure_radio_preset(self) -> bool:
"""Configure radio using settings from config.ini."""
if not self.meshcore:
return False
try:
cfg = config.get_config()
radio_config = cfg.get_radio_config()
freq_mhz = radio_config['frequency'] / 1000000 # Convert Hz to MHz
bw_khz = radio_config['bandwidth'] / 1000 # Convert Hz to kHz
sf = radio_config['spreading_factor']
cr = radio_config['coding_rate']
print("Configuring radio from config.ini...")
print(f" Frequency: {freq_mhz} MHz")
print(f" Bandwidth: {bw_khz} kHz")
print(f" Spreading Factor: {sf}")
print(f" Coding Rate: {cr}")
# Use meshcore_py set_radio command
# Parameters: freq (MHz), bw (kHz), sf (int), cr (int)
result = await self.meshcore.commands.set_radio(freq_mhz, bw_khz, sf, cr)
if result and result.type == EventType.OK:
print("Radio preset configured successfully")
print("Note: Radio settings will be applied after device reboot")
return True
elif result and result.type == EventType.ERROR:
print(f"Warning: Radio configuration returned error: {result.payload}")
# Continue anyway - settings might still be applied
return True
else:
print("Warning: Radio configuration returned unexpected result")
# Continue anyway
return True
except AttributeError:
# set_radio might not be available in this version
print("Warning: set_radio() not available in meshcore_py version")
print("Radio preset configuration may need to be done via mobile app or CLI")
return True
except Exception as e:
print(f"Error configuring preset: {e}")
print("Radio preset configuration may need to be done via mobile app or CLI")
# Continue anyway - don't block startup
return True
async def set_radio_name(self, name: str) -> bool:
"""Set radio name using meshcore_py."""
if not self.meshcore:
return False
try:
print(f"Setting radio name to: {name}")
result = await self.meshcore.commands.set_name(name)
if result and result.type == EventType.OK:
print(f"Radio name set to: {name}")
return True
elif result and result.type == EventType.ERROR:
print(f"Warning: Failed to set radio name: {result.payload}")
return False
else:
# Result might be None or unexpected - try to continue
print(f"Warning: Unexpected result when setting radio name")
return True
except AttributeError:
# set_name might not be available in this version
print("Warning: set_name() not available in meshcore_py version")
print("Radio name may need to be set via mobile app or CLI")
return True
except Exception as e:
print(f"Error setting radio name: {e}")
return False
async def send_flood_advert(self, count: int = 5, delay: float = 0.5):
"""Send flood adverts (multi-hop). Use every 24 hours."""
if not self.meshcore:
return
try:
for i in range(count):
await self.meshcore.commands.send_advert(flood=False)
if i < count - 1:
await asyncio.sleep(delay)
except Exception as e:
print(f"Error sending flood adverts: {e}")
async def send_zero_hop_advert(self, count: int = 5, delay: float = 0.5):
"""Send zero-hop adverts (local broadcast). Use every 24 hours."""
if not self.meshcore:
return
try:
for i in range(count):
await self.meshcore.commands.send_advert(flood=True)
if i < count - 1:
await asyncio.sleep(delay)
except Exception as e:
print(f"Error sending zero-hop adverts: {e}")
async def flood_advert(self, count: int = 5, delay: float = 0.5, zero_hop: bool = True):
"""
Send adverts. If zero_hop=True sends zero-hop; otherwise flood.
Prefer send_flood_advert() / send_zero_hop_advert() for scheduled use.
"""
if zero_hop:
await self.send_zero_hop_advert(count=count, delay=delay)
else:
await self.send_flood_advert(count=count, delay=delay)
async def send_public_message(self, text: str, channel: int = 0) -> bool:
"""Send a message to the public channel (channel 0)."""
if not self.meshcore:
return False
try:
result = await self.meshcore.commands.send_chan_msg(channel, text)
if result and result.type == EventType.ERROR:
print(f"Error sending public message: {result.payload}")
return False
return True
except Exception as e:
print(f"Error sending public message: {e}")
return False
async def discover_and_add_nodes(self):
"""Discover new nodes using meshcore_py contacts."""
if not self.meshcore:
return
try:
# Get contacts - these are discovered nodes
result = await self.meshcore.commands.get_contacts()
if not result:
return
if result.type == EventType.ERROR:
return
contacts = result.payload
if isinstance(contacts, dict):
for public_key, info in contacts.items():
if isinstance(public_key, str) and isinstance(info, dict):
pub_clean = public_key.lstrip("!").lower().strip()
if re.fullmatch(r'[a-f0-9]{8,}', pub_clean):
hex_id = pub_clean[:12] if len(pub_clean) >= 12 else pub_clean
if hex_id not in self.friends:
self.friends.add(hex_id)
except Exception as e:
print(f"Error discovering nodes: {e}")
def add_friend(self, node_id: str) -> bool:
"""Track a node locally."""
node_id = node_id.strip()
if node_id in self.friends:
return True
self.friends.add(node_id)
return True
def get_friends_list(self) -> list:
"""Get list of current friends."""
return list(self.friends)
async def disconnect(self):
"""Disconnect from MeshCore device."""
if self.meshcore:
try:
await self.meshcore.disconnect()
except Exception:
pass
self.meshcore = None