-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathbridge.py
More file actions
1370 lines (1282 loc) · 54 KB
/
bridge.py
File metadata and controls
1370 lines (1282 loc) · 54 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
from __future__ import annotations
import json
import os
import sys
import threading
import base64
import time
import zlib
import itertools
import traceback
from pathlib import Path
from dataclasses import dataclass, field
from typing import Any
_TAK_LOG_PATH = Path.cwd() / "data" / "tak_send_debug.log"
_TAK_LOG_PATH.parent.mkdir(parents=True, exist_ok=True)
_tak_log_lock = threading.Lock()
def _tak_log(msg: str) -> None:
ts = time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime())
line = f"[{ts}] {msg}\n"
with _tak_log_lock:
with open(_TAK_LOG_PATH, "a", encoding="utf-8") as f:
f.write(line)
from tak_fountain import (
MAX_PAYLOAD_SIZE,
TRANSFER_TYPE_COT,
TRANSFER_TYPE_COT_ASCII,
TYPE_COMPLETE,
TYPE_NEED_MORE,
AckPacket,
DataBlock,
EncodedBlock,
FountainCodec,
adaptive_overhead,
compute_hash,
generate_transfer_id,
get_packet_type,
is_fountain_packet,
)
def _tak_decompress(raw: bytes) -> str:
"""Decompress a TAK payload (zlib, raw deflate, or raw UTF-8 XML)."""
def _inflate_candidates(data: bytes) -> list[bytes]:
outputs: list[bytes] = []
for wbits in (zlib.MAX_WBITS, -zlib.MAX_WBITS):
try:
inflated = zlib.decompress(data, wbits)
except Exception:
continue
outputs.append(inflated)
if not outputs:
outputs.append(data)
return outputs
def _decode_xml_bytes(data: bytes) -> str:
for encoding in ("utf-8", "utf-8-sig", "utf-16", "utf-16-le", "utf-16-be"):
try:
text = data.decode(encoding)
except Exception:
continue
if text.lstrip().startswith("<"):
return text
return ""
for candidate in _inflate_candidates(raw):
text = _decode_xml_bytes(candidate)
if text:
return text
return ""
def _tak_payload_debug(raw: bytes) -> dict[str, Any]:
info: dict[str, Any] = {
"rawBytes": len(raw),
"rawPrefix": raw[:24].hex(),
}
for label, wbits in (("zlib", zlib.MAX_WBITS), ("raw-deflate", -zlib.MAX_WBITS)):
try:
inflated = zlib.decompress(raw, wbits)
except Exception:
continue
info[f"{label}Bytes"] = len(inflated)
info[f"{label}Prefix"] = inflated[:24].hex()
for encoding in ("utf-8", "utf-8-sig", "utf-16", "utf-16-le", "utf-16-be"):
try:
text = inflated.decode(encoding)
except Exception:
continue
preview = text[:120].replace("\n", " ").replace("\r", " ")
info[f"{label}Preview"] = preview
if text.lstrip().startswith("<"):
info[f"{label}Xml"] = True
return info
break
return info
def _xor_bytes(left: bytes | bytearray, right: bytes | bytearray) -> bytes:
size = min(len(left), len(right))
out = bytearray(left)
for idx in range(size):
out[idx] ^= right[idx]
return bytes(out)
def _matrix_rank_bitmasks(rows: list[int], width: int) -> int:
rank = 0
work = [row for row in rows if row]
bit = 0
while bit < width and rank < len(work):
pivot = None
for idx in range(rank, len(work)):
if work[idx] & (1 << bit):
pivot = idx
break
if pivot is None:
bit += 1
continue
work[rank], work[pivot] = work[pivot], work[rank]
for idx in range(len(work)):
if idx != rank and (work[idx] & (1 << bit)):
work[idx] ^= work[rank]
rank += 1
bit += 1
return rank
def _solve_source_blocks_from_masks(masks: list[int], payloads: list[bytes], source_block_count: int) -> list[bytes] | None:
rows: list[list[Any]] = [[mask, bytearray(payload)] for mask, payload in zip(masks, payloads)]
pivot_row_for_col = [-1] * source_block_count
row_index = 0
for col in range(source_block_count):
pivot = None
for idx in range(row_index, len(rows)):
if rows[idx][0] & (1 << col):
pivot = idx
break
if pivot is None:
continue
rows[row_index], rows[pivot] = rows[pivot], rows[row_index]
pivot_mask, pivot_payload = rows[row_index]
for idx in range(len(rows)):
if idx != row_index and (rows[idx][0] & (1 << col)):
rows[idx][0] ^= pivot_mask
rows[idx][1] = bytearray(_xor_bytes(rows[idx][1], pivot_payload))
pivot_row_for_col[col] = row_index
row_index += 1
if row_index == len(rows):
break
if any(idx < 0 for idx in pivot_row_for_col):
return None
solved = [b""] * source_block_count
for col, idx in enumerate(pivot_row_for_col):
row_mask, row_payload = rows[idx]
if row_mask != (1 << col):
return None
solved[col] = bytes(row_payload)
return solved
def _bruteforce_small_fountain_decode(blocks: list[EncodedBlock], source_block_count: int, total_length: int) -> bytes | None:
if source_block_count < 2 or source_block_count > 4 or len(blocks) < source_block_count:
return None
payloads = [bytes(block.payload) for block in blocks]
candidate_masks = list(range(1, 1 << source_block_count))
for masks in itertools.product(candidate_masks, repeat=len(blocks)):
if _matrix_rank_bitmasks(list(masks), source_block_count) < source_block_count:
continue
solved = _solve_source_blocks_from_masks(list(masks), payloads, source_block_count)
if not solved:
continue
valid = True
for mask, payload in zip(masks, payloads):
combined = bytes(len(payload))
for bit in range(source_block_count):
if mask & (1 << bit):
combined = _xor_bytes(combined, solved[bit])
if combined != payload:
valid = False
break
if not valid:
continue
actual_block_size = len(solved[0]) if solved else None
reassembled = _fountain_codec._reassemble(solved, total_length, actual_block_size)
if not reassembled or reassembled[0] not in (TRANSFER_TYPE_COT, TRANSFER_TYPE_COT_ASCII):
continue
payload_debug = _tak_payload_debug(reassembled[1:])
if _tak_decompress(reassembled[1:]) or payload_debug.get("zlibBytes") or payload_debug.get("raw-deflateBytes"):
return reassembled
return None
def _dump_failed_tak_payload(sender: str, transfer_id: int, decoded: bytes, blocks: list[EncodedBlock]) -> str:
stamp = int(time.time() * 1000)
safe_sender = str(sender).replace("!", "").replace(":", "_")
base = _tak_debug_dir / f"tak_{stamp}_{safe_sender}_{transfer_id}"
try:
raw_path = base.with_suffix(".bin")
raw_path.write_bytes(decoded)
meta = {
"sender": sender,
"transferId": transfer_id,
"decodedBytes": len(decoded),
"decodedPrefix": decoded[:64].hex(),
"payloadDebug": _tak_payload_debug(decoded[1:]) if len(decoded) > 1 else {},
"blocks": [
{
"seed": block.seed,
"sourceBlockCount": block.source_block_count,
"totalLength": block.total_length,
"sourceIndices": block.source_indices,
"payloadPrefix": bytes(block.payload[:32]).hex(),
"payloadBase64": base64.b64encode(bytes(block.payload)).decode("ascii"),
}
for block in blocks
],
}
meta_path = base.with_suffix(".json")
meta_path.write_text(json.dumps(meta, ensure_ascii=False, indent=2), encoding="utf-8")
return str(meta_path)
except Exception:
return ""
def _dump_tak_plugin_payload(sender: str, raw_payload: bytes, channel_index: int | None, hop_limit: int | None) -> str:
stamp = int(time.time() * 1000)
safe_sender = str(sender).replace("!", "").replace(":", "_")
base = _tak_plugin_debug_dir / f"atak_plugin_{stamp}_{safe_sender}"
try:
raw_path = base.with_suffix(".bin")
raw_path.write_bytes(raw_payload)
meta = {
"sender": sender,
"channelIndex": channel_index,
"hopLimit": hop_limit,
"payloadBytes": len(raw_payload),
"payloadPrefix": raw_payload[:64].hex(),
"payloadBase64": base64.b64encode(raw_payload).decode("ascii"),
}
meta_path = base.with_suffix(".json")
meta_path.write_text(json.dumps(meta, ensure_ascii=False, indent=2), encoding="utf-8")
return str(meta_path)
except Exception:
return ""
def _extract_payload_bytes(value: Any) -> bytes | None:
if isinstance(value, (bytes, bytearray, memoryview)):
return bytes(value)
if isinstance(value, list):
try:
return bytes(int(item) & 0xFF for item in value)
except Exception:
return None
if isinstance(value, str):
stripped = value.strip()
if not stripped:
return None
if stripped.startswith("<"):
return stripped.encode("utf-8")
compact = stripped.replace(" ", "")
if len(compact) % 2 == 0:
try:
return bytes.fromhex(compact)
except Exception:
return stripped.encode("utf-8")
return stripped.encode("utf-8")
return None
_fountain_codec = FountainCodec(MAX_PAYLOAD_SIZE)
_fountain_lock = threading.Lock()
_fountain_send_states: dict[int, "SendState"] = {}
_fountain_receive_states: dict[tuple[str, int], "ReceiveState"] = {}
_tak_debug_dir = Path.cwd() / "data" / "tak_debug"
_tak_debug_dir.mkdir(parents=True, exist_ok=True)
_tak_plugin_debug_dir = Path.cwd() / "data" / "tak_plugin_debug"
_tak_plugin_debug_dir.mkdir(parents=True, exist_ok=True)
@dataclass(slots=True)
class SendState:
transfer_id: int
data_hash: bytes
source_block_count: int
condition: threading.Condition
is_complete: bool = False
ack_received: bool = False
need_more_blocks: int = 0
@dataclass(slots=True)
class ReceiveState:
transfer_id: int
sender: str
channel_index: int
hop_limit: int | None
source_block_count: int
total_length: int
blocks: dict[int, EncodedBlock] = field(default_factory=dict)
is_complete: bool = False
last_activity: float = field(default_factory=time.time)
def _resolve_channel_index(packet: dict[str, Any], decoded: dict[str, Any]) -> int:
for key in ("channel", "channelIndex"):
value = packet.get(key)
if isinstance(value, int):
return value
value = decoded.get(key)
if isinstance(value, int):
return value
return 0
def _prune_fountain_receive_states() -> None:
now = time.time()
stale_keys = [
key for key, state in _fountain_receive_states.items()
if now - state.last_activity > 300
]
for key in stale_keys:
del _fountain_receive_states[key]
def _send_fountain_ack(
mesh_interface: Any,
tak_portnum: int,
destination_id: str,
channel_index: int,
hop_limit: int | None,
transfer_id: int,
packet_type: int,
received_blocks: int,
needed_blocks: int,
data_hash: bytes,
) -> None:
payload = AckPacket(
transfer_id=transfer_id,
packet_type=packet_type,
received_blocks=received_blocks,
needed_blocks=needed_blocks,
data_hash=data_hash,
).to_bytes()
mesh_interface.sendData(
payload,
destinationId=destination_id,
portNum=tak_portnum,
wantAck=False,
channelIndex=channel_index,
hopLimit=hop_limit,
)
def _handle_fountain_ack(raw_payload: bytes) -> None:
ack = AckPacket.from_bytes(raw_payload)
if ack is None:
return
with _fountain_lock:
state = _fountain_send_states.get(ack.transfer_id)
if state is None:
return
state.ack_received = True
if ack.packet_type == TYPE_COMPLETE:
if ack.data_hash == state.data_hash:
state.is_complete = True
else:
state.need_more_blocks = max(1, state.source_block_count // 4)
elif ack.packet_type == TYPE_NEED_MORE:
state.need_more_blocks = max(1, ack.needed_blocks)
state.condition.notify_all()
def _handle_fountain_data(
raw_payload: bytes,
sender: str,
channel_index: int,
hop_limit: int | None,
mesh_interface: Any,
tak_portnum: int,
) -> str:
data_block = DataBlock.from_bytes(raw_payload)
if data_block is None:
return ""
ack_payload: tuple[int, int, bytes] | None = None
transfer_type = -1
payload = b""
block_count = 0
blocks_snapshot: list[EncodedBlock] = []
with _fountain_lock:
_prune_fountain_receive_states()
key = (sender, data_block.transfer_id)
state = _fountain_receive_states.get(key)
if state is None:
state = ReceiveState(
transfer_id=data_block.transfer_id,
sender=sender,
channel_index=channel_index,
hop_limit=hop_limit,
source_block_count=data_block.source_block_count,
total_length=data_block.total_length,
)
_fountain_receive_states[key] = state
elif state.is_complete:
return ""
elif (
state.source_block_count != data_block.source_block_count
or state.total_length != data_block.total_length
):
state = ReceiveState(
transfer_id=data_block.transfer_id,
sender=sender,
channel_index=channel_index,
hop_limit=hop_limit,
source_block_count=data_block.source_block_count,
total_length=data_block.total_length,
)
_fountain_receive_states[key] = state
if data_block.seed in state.blocks:
state.last_activity = time.time()
return ""
state.blocks[data_block.seed] = EncodedBlock(
seed=data_block.seed,
source_block_count=data_block.source_block_count,
total_length=data_block.total_length,
source_indices=_fountain_codec.regenerate_indices(
data_block.seed,
data_block.source_block_count,
data_block.transfer_id,
),
payload=data_block.payload,
)
state.last_activity = time.time()
block_count = len(state.blocks)
blocks_snapshot = list(state.blocks.values())
if len(state.blocks) < state.source_block_count:
return ""
decoded = _fountain_codec.decode(blocks_snapshot)
if not decoded:
decoded = _bruteforce_small_fountain_decode(
blocks_snapshot,
data_block.source_block_count,
data_block.total_length,
)
elif decoded:
transfer_type_probe = decoded[0]
if transfer_type_probe in (TRANSFER_TYPE_COT, TRANSFER_TYPE_COT_ASCII) and not _tak_decompress(decoded[1:]):
fallback_decoded = _bruteforce_small_fountain_decode(
blocks_snapshot,
data_block.source_block_count,
data_block.total_length,
)
if fallback_decoded:
decoded = fallback_decoded
if not decoded:
emit("tak_debug", {
"direction": "rx",
"sender": sender,
"recipient": "local",
"portnum": "ATAK_FORWARDER",
"channelIndex": channel_index,
"hopLimit": hop_limit,
"decode": "fountain-decode-failed",
"transferId": data_block.transfer_id,
"blocksReceived": len(state.blocks),
"sourceBlockCount": data_block.source_block_count,
"totalLength": data_block.total_length,
})
return ""
transfer_type = decoded[0]
payload = decoded[1:]
state.is_complete = True
ack_hash = compute_hash(decoded)
ack_payload = (data_block.transfer_id, len(state.blocks), ack_hash)
del _fountain_receive_states[key]
if ack_payload is not None:
transfer_id, received_blocks, ack_hash = ack_payload
_send_fountain_ack(
mesh_interface,
tak_portnum,
sender,
channel_index,
hop_limit,
transfer_id,
TYPE_COMPLETE,
received_blocks,
0,
ack_hash,
)
time.sleep(0.2)
_send_fountain_ack(
mesh_interface,
tak_portnum,
sender,
channel_index,
hop_limit,
transfer_id,
TYPE_COMPLETE,
received_blocks,
0,
ack_hash,
)
cot_xml = ""
if transfer_type in (TRANSFER_TYPE_COT, TRANSFER_TYPE_COT_ASCII):
cot_xml = _tak_decompress(payload)
dump_path = ""
if transfer_type in (TRANSFER_TYPE_COT, TRANSFER_TYPE_COT_ASCII) and not cot_xml:
dump_path = _dump_failed_tak_payload(
sender,
data_block.transfer_id,
bytes([transfer_type]) + payload,
blocks_snapshot,
)
if transfer_type != -1:
note = ""
if payload[:1] == b"\xEE":
note = "decoded payload starts with 0xEE; Meshtastic Extra Encryption is likely enabled on sender"
if not note and payload[:4] == b"$EXI":
note = "decoded payload starts with $EXI; sender may be using EXI instead of raw XML"
if dump_path:
note = f"{note} dump={dump_path}".strip()
payload_prefix = payload[:16].hex()
payload_debug = _tak_payload_debug(payload) if not cot_xml else {}
emit("tak_debug", {
"direction": "rx",
"sender": sender,
"recipient": "local",
"portnum": "ATAK_FORWARDER",
"channelIndex": channel_index,
"hopLimit": hop_limit,
"decode": "fountain-complete",
"transferId": data_block.transfer_id,
"blocksReceived": block_count,
"sourceBlockCount": data_block.source_block_count,
"totalLength": data_block.total_length,
"transferType": transfer_type,
"payloadBytes": len(payload),
"payloadPrefix": payload_prefix,
"cotXmlBytes": len(cot_xml.encode("utf-8")) if cot_xml else 0,
"payloadDebug": payload_debug,
"note": note,
})
return cot_xml
def _send_fountain_transfer(
mesh_interface: Any,
tak_portnum: int,
destination_id: str,
cot_xml: str,
channel_index: int = 0,
hop_limit: int | None = None,
local_sender_id: str = "",
) -> dict[str, Any]:
compressed = zlib.compress(cot_xml.encode("utf-8"), level=9)
_tak_log(f"SEND_START xml_chars={len(cot_xml)} compressed_bytes={len(compressed)} dest={destination_id} channel={channel_index} hop_limit={hop_limit} portnum={tak_portnum} interface_type={type(mesh_interface).__name__}")
_tak_log(f"SEND_XML_PREVIEW {cot_xml[:200]}")
if len(compressed) <= 231:
try:
mesh_interface.sendData(
compressed,
destinationId=destination_id,
portNum=tak_portnum,
wantAck=False,
channelIndex=channel_index,
hopLimit=hop_limit,
)
_tak_log(f"SEND_DIRECT_OK compressed_bytes={len(compressed)}")
except Exception as exc:
_tak_log(f"SEND_DIRECT_ERROR {exc}\n{traceback.format_exc()}")
raise
return {"mode": "direct", "compressedBytes": len(compressed), "blocksSent": 1, "transferId": None}
data_with_type = bytes([TRANSFER_TYPE_COT]) + compressed
transfer_id = generate_transfer_id(local_sender_id)
source_block_count = _fountain_codec.get_source_block_count(len(data_with_type))
blocks_to_send = _fountain_codec.get_recommended_block_count(
len(data_with_type),
adaptive_overhead(source_block_count),
)
condition = threading.Condition(_fountain_lock)
state = SendState(
transfer_id=transfer_id,
data_hash=compute_hash(data_with_type),
source_block_count=source_block_count,
condition=condition,
)
with _fountain_lock:
_fountain_send_states[transfer_id] = state
_tak_log(f"SEND_FOUNTAIN_START transfer_id={transfer_id} source_blocks={source_block_count} blocks_to_send={blocks_to_send} total_bytes={len(data_with_type)}")
try:
inter_packet_delay = max(0.25, float(os.environ.get("TAK_FOUNTAIN_INTER_PACKET_DELAY_SEC", "1.6")))
except Exception:
inter_packet_delay = 1.6
try:
per_packet_time_ms = max(100, int(os.environ.get("TAK_FOUNTAIN_PACKET_TIME_MS", "3200")))
except Exception:
per_packet_time_ms = 3200
try:
attempt = 0
while attempt < 3 and not state.is_complete:
attempt += 1
with _fountain_lock:
state.ack_received = False
blocks = _fountain_codec.encode(data_with_type, blocks_to_send, transfer_id)
_tak_log(f"SEND_FOUNTAIN_ATTEMPT attempt={attempt} blocks={len(blocks)}")
for i, block in enumerate(blocks):
packet = DataBlock(
transfer_id=transfer_id,
seed=block.seed,
source_block_count=block.source_block_count,
total_length=block.total_length,
payload=block.payload,
).to_bytes()
try:
mesh_interface.sendData(
packet,
destinationId=destination_id,
portNum=tak_portnum,
wantAck=False,
channelIndex=channel_index,
hopLimit=hop_limit,
)
_tak_log(f"SEND_FOUNTAIN_BLOCK_OK block={i+1}/{len(blocks)} packet_bytes={len(packet)}")
except Exception as exc:
_tak_log(f"SEND_FOUNTAIN_BLOCK_ERROR block={i+1}/{len(blocks)} {exc}\n{traceback.format_exc()}")
raise
time.sleep(inter_packet_delay)
timeout = min(300.0, (10000 + blocks_to_send * per_packet_time_ms * 2 + per_packet_time_ms * 4) / 1000.0)
_tak_log(f"SEND_FOUNTAIN_WAIT_ACK timeout={timeout:.1f}s")
with _fountain_lock:
state.condition.wait_for(lambda: state.ack_received or state.is_complete, timeout=timeout)
if state.is_complete:
_tak_log(f"SEND_FOUNTAIN_ACK_COMPLETE transfer_id={transfer_id}")
return {
"mode": "fountain",
"compressedBytes": len(compressed),
"blocksSent": blocks_to_send,
"transferId": transfer_id,
}
if state.need_more_blocks > 0:
_tak_log(f"SEND_FOUNTAIN_NEED_MORE need={state.need_more_blocks}")
blocks_to_send = state.need_more_blocks
state.need_more_blocks = 0
else:
blocks_to_send = max(5, source_block_count // 5)
_tak_log(f"SEND_FOUNTAIN_TIMEOUT_RETRY blocks_to_send={blocks_to_send}")
_tak_log(f"SEND_FOUNTAIN_UNCONFIRMED transfer_id={transfer_id} all_attempts_done")
return {
"mode": "fountain-unconfirmed",
"compressedBytes": len(compressed),
"blocksSent": blocks_to_send,
"transferId": transfer_id,
}
finally:
with _fountain_lock:
_fountain_send_states.pop(transfer_id, None)
if hasattr(sys.stdin, "reconfigure"):
sys.stdin.reconfigure(encoding="utf-8")
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8")
if hasattr(sys.stderr, "reconfigure"):
sys.stderr.reconfigure(encoding="utf-8")
def emit(message_type: str, payload: dict[str, Any]) -> None:
sys.stdout.write(json.dumps({"type": message_type, "payload": payload}, ensure_ascii=True) + "\n")
sys.stdout.flush()
def repair_text(value: Any) -> str:
text = str(value or "")
if not text:
return ""
if "Р" in text or "Ñ" in text:
for source_encoding in ("cp1251", "latin1"):
try:
repaired = text.encode(source_encoding).decode("utf-8")
except Exception:
continue
if repaired and repaired != text:
text = repaired
break
return text
def sanitize_for_json(value: Any) -> Any:
if isinstance(value, dict):
return {str(key): sanitize_for_json(item) for key, item in value.items()}
if isinstance(value, (list, tuple, set)):
return [sanitize_for_json(item) for item in value]
if isinstance(value, bytes):
try:
return value.decode("utf-8")
except Exception:
return value.hex()
if isinstance(value, str):
return repair_text(value)
if value is None or isinstance(value, (bool, int, float)):
return value
return str(value)
def describe_serial_port(port: Any) -> dict[str, Any]:
return {
"device": str(getattr(port, "device", "") or ""),
"name": repair_text(getattr(port, "name", "") or ""),
"description": repair_text(getattr(port, "description", "") or ""),
"manufacturer": repair_text(getattr(port, "manufacturer", "") or ""),
"product": repair_text(getattr(port, "product", "") or ""),
"serialNumber": repair_text(getattr(port, "serial_number", "") or ""),
"location": repair_text(getattr(port, "location", "") or ""),
"interface": repair_text(getattr(port, "interface", "") or ""),
"hwid": repair_text(getattr(port, "hwid", "") or ""),
"vid": getattr(port, "vid", None),
"pid": getattr(port, "pid", None),
}
def list_serial_ports() -> list[dict[str, Any]]:
try:
from serial.tools import list_ports # type: ignore
except Exception:
return []
return [describe_serial_port(port) for port in list_ports.comports()]
def looks_like_meshtastic_port(port: dict[str, Any]) -> bool:
combined = " ".join(
str(port.get(key, "") or "")
for key in ("description", "manufacturer", "product", "hwid", "device")
).lower()
keywords = (
"meshtastic",
"heltec",
"rak",
"lora",
"nrf",
"cp210",
"ch340",
"usb serial",
"uart",
"silicon labs",
"wch",
)
return any(keyword in combined for keyword in keywords)
def detect_port_candidates(find_ports: Any) -> tuple[list[str], list[dict[str, Any]], list[str]]:
detected_ports: list[str] = []
try:
detected_ports = [str(port) for port in (find_ports(True) or []) if port]
except Exception:
detected_ports = []
available_ports = list_serial_ports()
fallback_ports: list[str] = []
for port in available_ports:
device = str(port.get("device") or "")
if not device or device in detected_ports:
continue
if looks_like_meshtastic_port(port):
fallback_ports.append(device)
return detected_ports, available_ports, fallback_ports
def snapshot_nodes(interface: Any) -> list[dict[str, Any]]:
nodes: list[dict[str, Any]] = []
raw_nodes = getattr(interface, "nodes", {}) or {}
local_node_num = str(
getattr(getattr(interface, "localNode", None), "nodeNum", None)
or getattr(getattr(interface, "myInfo", None), "myNodeNum", None)
or ""
)
local_modem_preset = ""
try:
from meshtastic.protobuf import config_pb2 # type: ignore
local_lora = getattr(getattr(getattr(interface, "localNode", None), "localConfig", None), "lora", None)
preset_value = getattr(local_lora, "modem_preset", None)
if preset_value is not None:
local_modem_preset = str(config_pb2.Config.LoRaConfig.ModemPreset.Name(int(preset_value)) or "")
except Exception:
local_modem_preset = ""
for node_id, node in raw_nodes.items():
user = node.get("user", {}) or {}
position = node.get("position", {}) or {}
metrics = node.get("deviceMetrics", {}) or {}
environment = node.get("environmentMetrics", {}) or {}
neighbor_info = node.get("neighborInfo", {}) or {}
neighbors = [
{"nodeId": str(int(n.get("nodeId") or 0)), "snr": n.get("snr")}
for n in (neighbor_info.get("neighbors") or [])
if n.get("nodeId")
]
nodes.append(
{
"id": str(node.get("num") or node_id or user.get("id") or "unknown"),
"userId": str(user.get("id") or ""),
"shortName": repair_text(user.get("shortName") or ""),
"longName": repair_text(user.get("longName") or ""),
"hardware": str(user.get("hwModel") or ""),
"meshtasticRole": str(user.get("role") or ""),
"lastHeard": node.get("lastHeard"),
"snr": node.get("snr"),
"hopsAway": node.get("hopsAway"),
"batteryLevel": metrics.get("batteryLevel"),
"voltage": metrics.get("voltage"),
"latitude": position.get("latitude"),
"longitude": position.get("longitude"),
"modemPreset": local_modem_preset if str(node.get("num") or node_id or "") == local_node_num else "",
"environmentMetrics": environment,
"neighbors": neighbors,
"raw": sanitize_for_json(node),
}
)
return nodes
def main() -> int:
try:
from pubsub import pub # type: ignore
from meshtastic.serial_interface import SerialInterface # type: ignore
from meshtastic.util import findPorts # type: ignore
except Exception as exc:
emit("status", {"connected": False, "mode": "error", "error": f"bridge import failed: {exc}"})
return 1
if "--list-ports" in sys.argv[1:]:
detected_ports, available_ports, fallback_ports = detect_port_candidates(findPorts)
sys.stdout.write(
json.dumps(
{
"ports": available_ports,
"detectedPorts": detected_ports,
"fallbackPorts": fallback_ports,
},
ensure_ascii=True,
)
+ "\n"
)
sys.stdout.flush()
return 0
requested_port = os.getenv("MESHTASTIC_PORT") or None
port = requested_port
detected_ports: list[str] = []
available_ports: list[dict[str, Any]] = []
fallback_ports: list[str] = []
if not port:
try:
detected_ports, available_ports, fallback_ports = detect_port_candidates(findPorts)
except Exception as exc:
emit("status", {"connected": False, "mode": "error", "error": f"port detection failed: {exc}"})
return 1
if detected_ports:
port = detected_ports[0]
elif len(fallback_ports) == 1:
port = fallback_ports[0]
elif len(available_ports) == 1:
port = str(available_ports[0].get("device") or "")
if not port:
emit(
"status",
{
"connected": False,
"mode": "error",
"error": "no Meshtastic serial ports detected",
"port": None,
"detectedPorts": detected_ports,
"fallbackPorts": fallback_ports,
"availablePorts": available_ports,
},
)
return 1
emit(
"status",
{
"connected": False,
"mode": "detecting",
"port": port,
"detectedPorts": detected_ports,
"fallbackPorts": fallback_ports,
"availablePorts": available_ports,
"warning": (
None
if len(detected_ports) == 1
else (
f"multiple ports detected, auto-selecting {port}"
if detected_ports
else f"Meshtastic auto-detect missed the device, trying fallback port {port}"
)
),
},
)
try:
interface = SerialInterface(devPath=port, timeout=8)
except Exception as exc:
emit(
"status",
{
"connected": False,
"mode": "error",
"error": f"serial connect failed: {exc}",
"port": port,
"detectedPorts": detected_ports,
"fallbackPorts": fallback_ports,
"availablePorts": available_ports,
},
)
return 1
emit(
"status",
{
"connected": True,
"mode": "serial",
"port": port,
"detectedPorts": detected_ports if detected_ports else [port],
"fallbackPorts": fallback_ports,
"availablePorts": available_ports,
"source": "env" if requested_port else "auto",
"localNodeId": str(
getattr(getattr(interface, "localNode", None), "nodeNum", None)
or getattr(getattr(interface, "myInfo", None), "myNodeNum", None)
or ""
),
},
)
emit("nodes", {"nodes": snapshot_nodes(interface)})
mesh_interface = interface
def on_receive(packet: dict[str, Any], interface: Any | None = None, topic: Any | None = None, **kwargs: Any) -> None:
decoded = packet.get("decoded", {})
text = decoded.get("text")
telemetry = decoded.get("telemetry")
portnum = str(decoded.get("portnum") or "")
channel_index = _resolve_channel_index(packet, decoded)
sender = str(packet.get("fromId") or packet.get("from") or "unknown")
recipient = str(packet.get("toId") or packet.get("to") or "local-ai")
to_id = str(packet.get("toId") or "")
is_direct_message = to_id not in ("", "^all")
active_interface = interface or kwargs.get("interface") or mesh_interface
emit("nodes", {"nodes": snapshot_nodes(active_interface)})
relay_node = packet.get("relayNode") or None
hop_start = packet.get("hopStart")
hop_limit = packet.get("hopLimit")
rx_snr = packet.get("rxSnr")
emit(
"packet",
{
"sender": sender,
"recipient": recipient,
"transport": "serial",
"isDirectMessage": is_direct_message,
"portnum": portnum,
"relayNode": relay_node,
"hopStart": hop_start,
"hopLimit": hop_limit,
"rxSnr": rx_snr,
"channelIndex": channel_index,
"decoded": sanitize_for_json(decoded),
"packet": sanitize_for_json(packet),
},
)
if portnum == "ROUTING_APP":
request_id = decoded.get("requestId")
if request_id is not None:
routing = decoded.get("routing", {})
error_reason = str(routing.get("errorReason") or "NONE")
emit("ack", {
"packetId": request_id,
"errorReason": error_reason,
"from": sender,
})
return
# portNum 72 (ATAK_PLUGIN): PLI / GeoChat wrapped in TAKPacket protobuf
# portNum 257 (ATAK_FORWARDER): zlib-compressed CoT XML for map items (waypoints, routes, polygons)
if portnum in ("TAK_APP", "ATAK_PLUGIN"):
raw_payload = _extract_payload_bytes(decoded.get("payload"))
dump_path = _dump_tak_plugin_payload(
sender,
raw_payload or b"",
channel_index,
hop_limit if isinstance(hop_limit, int) else None,
) if raw_payload else ""
emit("tak_debug", {