-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathmqtt-connect.py
executable file
·1755 lines (1307 loc) · 60.6 KB
/
mqtt-connect.py
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
"""
MQTT Connect for Meshtastic Version 0.8.7 by https://github.com/pdxlocations
Many thanks to and protos code from: https://github.com/arankwende/meshtastic-mqtt-client & https://github.com/joshpirihi/meshtastic-mqtt
Encryption/Decryption help from: https://github.com/dstewartgo
Powered by Meshtastic™ https://meshtastic.org/
"""
#### Imports
try:
from meshtastic.protobuf import mesh_pb2, mqtt_pb2, portnums_pb2, telemetry_pb2
from meshtastic import BROADCAST_NUM
except ImportError:
from meshtastic import mesh_pb2, mqtt_pb2, portnums_pb2, telemetry_pb2, BROADCAST_NUM
import random
import threading
import sqlite3
import time
import ssl
import string
import sys
from datetime import datetime
from time import mktime
from typing import Optional
import tkinter as tk
from tkinter import scrolledtext, simpledialog, messagebox
import tkinter.messagebox
import base64
import json
import re
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
import paho.mqtt.client as mqtt
#################################
### Debug Options
debug: bool = False
auto_reconnect: bool = False
auto_reconnect_delay: float = 1 # seconds
print_service_envelope: bool = False
print_message_packet: bool = False
print_text_message: bool = False
print_node_info: bool = False
print_telemetry: bool = False
print_failed_encryption_packet: bool = False
print_position_report: bool = False
color_text: bool = False
display_encrypted_emoji: bool = True
display_dm_emoji: bool = True
display_lookup_button: bool = False
display_private_dms: bool = False
record_locations: bool = False
#################################
### Default settings
mqtt_broker = "mqtt.meshtastic.org"
mqtt_port = 1883
mqtt_username = "meshdev"
mqtt_password = "large4cats"
root_topic = "msh/US/2/e/"
channel = "LongFast"
key = "AQ=="
max_msg_len = mesh_pb2.Constants.DATA_PAYLOAD_LEN
key_emoji = "\U0001F511"
encrypted_emoji = "\U0001F512"
dm_emoji = "\u2192"
client_short_name = "MCM"
client_long_name = "MQTTastic"
lat = ""
lon = ""
alt = ""
client_hw_model = 255
node_info_interval_minutes = 15
#################################
### Program variables
default_key = "1PG7OiApB1nwvP+rz05pAQ==" # AKA AQ==
db_file_path = "mmc.db"
presets_file_path = "presets.json"
presets = {}
reserved_ids = [1,2,3,4,4294967295]
#################################
### Program Base Functions
def is_valid_hex(test_value: str, minchars: Optional[int], maxchars: int) -> bool:
"""Check if the provided string is valid hex. Note that minchars and maxchars count INDIVIDUAL HEX LETTERS, inclusive. Setting either to None means you don't care about that one."""
if test_value.startswith('!'):
test_value = test_value[1:] #Ignore a leading exclamation point
valid_hex_return: bool = all(c in string.hexdigits for c in test_value)
decimal_value = int(test_value, 16)
if decimal_value in reserved_ids:
return False
if minchars is not None:
valid_hex_return = valid_hex_return and (minchars <= len(test_value))
if maxchars is not None:
valid_hex_return = valid_hex_return and (len(test_value) <= maxchars)
return valid_hex_return
def set_topic():
"""?"""
if debug:
print("set_topic")
global subscribe_topic, publish_topic, node_number, node_name
node_name = '!' + hex(node_number)[2:]
subscribe_topic = root_topic + channel + "/#"
publish_topic = root_topic + channel + "/" + node_name
def current_time() -> str:
"""Return the current time (as an integer number of seconds since the epoch) as a string."""
current_time_str = str(int(time.time()))
return current_time_str
def format_time(time_str: str) -> str:
"""Convert the time string (number of seconds since the epoch) back to a datetime object."""
timestamp: int = int(time_str)
time_dt: datetime = datetime.fromtimestamp(timestamp)
# Get the current datetime for comparison
now = datetime.now()
# Check if the provided time is from today
if time_dt.date() == now.date():
# If it's today, format as "H:M am/pm"
time_formatted = time_dt.strftime("%I:%M %p")
else:
# If it's not today, format as "DD/MM/YY H:M:S"
time_formatted = time_dt.strftime("%d/%m/%y %H:%M:%S")
return time_formatted
def xor_hash(data: bytes) -> int:
"""Return XOR hash of all bytes in the provided string."""
result = 0
for char in data:
result ^= char
return result
def generate_hash(name: str, key: str) -> int:
"""?"""
replaced_key = key.replace('-', '+').replace('_', '/')
key_bytes = base64.b64decode(replaced_key.encode('utf-8'))
h_name = xor_hash(bytes(name, 'utf-8'))
h_key = xor_hash(key_bytes)
result: int = h_name ^ h_key
return result
def get_name_by_id(name_type: str, user_id: str) -> str:
"""See if we have a (long or short, as specified by "name_type") name for the given user_id."""
# Convert the user_id to hex and prepend '!'
hex_user_id: str = '!%08x' % user_id
try:
table_name = sanitize_string(mqtt_broker) + "_" + sanitize_string(root_topic) + sanitize_string(channel) + "_nodeinfo"
with sqlite3.connect(db_file_path) as db_connection:
db_cursor = db_connection.cursor()
# Fetch the name based on the hex user ID
if name_type == "long":
result = db_cursor.execute(f'SELECT long_name FROM {table_name} WHERE user_id=?', (hex_user_id,)).fetchone()
if name_type == "short":
result = db_cursor.execute(f'SELECT short_name FROM {table_name} WHERE user_id=?', (hex_user_id,)).fetchone()
if result:
if debug:
print("found user in db: " + str(hex_user_id))
return result[0]
# If we don't find a user id in the db, ask for an id
else:
if user_id != BROADCAST_NUM:
if debug:
print("didn't find user in db: " + str(hex_user_id))
send_node_info(user_id, want_response=True) # DM unknown user a nodeinfo with want_response
return f"Unknown User ({hex_user_id})"
except sqlite3.Error as e:
print(f"SQLite error in get_name_by_id: {e}")
finally:
db_connection.close()
return f"Unknown User ({hex_user_id})"
def sanitize_string(input_str: str) -> str:
"""Check if the string starts with a letter (a-z, A-Z) or an underscore (_), and replace all non-alpha/numeric/underscore characters with underscores."""
if not re.match(r'^[a-zA-Z_]', input_str):
# If not, add "_"
input_str = '_' + input_str
# Replace special characters with underscores (for database tables)
sanitized_str: str = re.sub(r'[^a-zA-Z0-9_]', '_', input_str)
return sanitized_str
#################################
# Handle Presets
class Preset:
"""Values needed to remember settings between runs."""
def __init__(self, name, broker, username, password, root_topic, channel, key, node_number, long_name, short_name, lat, lon, alt):
"""Pull in provided values."""
self.name = name
self.broker = broker
self.username = username
self.password = password
self.root_topic = root_topic
self.channel = channel
self.key = key
self.node_number = node_number
self.long_name = long_name
self.short_name = short_name
self.lat = lat
self.lon = lon
self.alt = alt
def to_dict(self):
"""Format provided values as a dictionary."""
return {
'name': self.name,
'broker': self.broker,
'username': self.username,
'password': self.password,
'root_topic': self.root_topic,
'channel': self.channel,
'key': self.key,
'node_number': self.node_number,
'long_name': self.long_name,
'short_name': self.short_name,
'lat': self.lat,
'lon': self.lon,
'alt': self.alt
}
def save_preset():
"""Save preset values to disk."""
if debug:
print("save_preset")
name = tkinter.simpledialog.askstring("Save Preset", "Enter preset name:")
# Check if the user clicked Cancel
if name is None:
return
preset = Preset(name, mqtt_broker_entry.get(), mqtt_username_entry.get(), mqtt_password_entry.get(), root_topic_entry.get(),
channel_entry.get(), key_entry.get(), node_number_entry.get(), long_name_entry.get(), short_name_entry.get(), lat_entry.get(), lon_entry.get(), alt_entry.get())
presets[name] = preset # Store the Preset object directly
update_preset_dropdown()
preset_var.set(name)
save_presets_to_file()
def load_preset():
"""Function to load the selected preset."""
if debug:
print("load_preset")
selected_preset_name = preset_var.get()
if selected_preset_name in presets:
selected_preset = presets[selected_preset_name]
if debug:
print(f"Loading preset: {selected_preset_name}")
mqtt_broker_entry.delete(0, tk.END)
mqtt_broker_entry.insert(0, selected_preset.broker)
mqtt_username_entry.delete(0, tk.END)
mqtt_username_entry.insert(0, selected_preset.username)
mqtt_password_entry.delete(0, tk.END)
mqtt_password_entry.insert(0, selected_preset.password)
root_topic_entry.delete(0, tk.END)
root_topic_entry.insert(0, selected_preset.root_topic)
channel_entry.delete(0, tk.END)
channel_entry.insert(0, selected_preset.channel)
key_entry.delete(0, tk.END)
key_entry.insert(0, selected_preset.key)
node_number_entry.delete(0, tk.END)
node_number_entry.insert(0, selected_preset.node_number)
move_text_down()
long_name_entry.delete(0, tk.END)
long_name_entry.insert(0, selected_preset.long_name)
short_name_entry.delete(0, tk.END)
short_name_entry.insert(0, selected_preset.short_name)
lat_entry.delete(0, tk.END)
lat_entry.insert(0, selected_preset.lat)
lon_entry.delete(0, tk.END)
lon_entry.insert(0, selected_preset.lon)
alt_entry.delete(0, tk.END)
alt_entry.insert(0, selected_preset.alt)
else:
print(f"Error: Preset '{selected_preset_name}' not found.")
def update_preset_dropdown():
"""Update the preset dropdown menu."""
preset_names = list(presets.keys())
menu = preset_dropdown["menu"]
menu.delete(0, 'end')
for preset_name in preset_names:
menu.add_command(label=preset_name, command=tk._setit(preset_var, preset_name, lambda *args: load_preset()))
def preset_var_changed(*args):
"""?"""
selected_option = preset_var.get()
update_preset_dropdown()
print(f"Selected Option: {selected_option}")
def save_presets_to_file():
"""?"""
if debug:
print("save_presets_to_file")
with open(presets_file_path, "w") as file:
json.dump({name: preset.__dict__ for name, preset in presets.items()}, file, indent=2)
def load_presets_from_file():
"""Load presets from a file."""
if debug:
print("load_presets_from_file")
try:
with open(presets_file_path, "r") as file:
loaded_presets = json.load(file)
return {name: Preset(**data) for name, data in loaded_presets.items()}
except FileNotFoundError:
return {}
#################################
# Receive Messages
def on_message(client, userdata, msg): # pylint: disable=unused-argument
"""Callback function that accepts a meshtastic message from mqtt."""
# if debug:
# print("on_message")
se = mqtt_pb2.ServiceEnvelope()
is_encrypted: bool = False
try:
se.ParseFromString(msg.payload)
if print_service_envelope:
print ("")
print ("Service Envelope:")
print (se)
mp = se.packet
except Exception as e:
print(f"*** ServiceEnvelope: {str(e)}")
return
if len(msg.payload) > max_msg_len:
if debug:
print('Message too long: ' + str(len(msg.payload)) + ' bytes long, skipping.')
return
if mp.HasField("encrypted") and not mp.HasField("decoded"):
decode_encrypted(mp)
is_encrypted=True
if print_message_packet:
print ("")
print ("Message Packet:")
print(mp)
if mp.decoded.portnum == portnums_pb2.TEXT_MESSAGE_APP:
try:
text_payload = mp.decoded.payload.decode("utf-8")
process_message(mp, text_payload, is_encrypted)
# print(f"{text_payload}")
except Exception as e:
print(f"*** TEXT_MESSAGE_APP: {str(e)}")
elif mp.decoded.portnum == portnums_pb2.NODEINFO_APP:
info = mesh_pb2.User()
try:
info.ParseFromString(mp.decoded.payload)
maybe_store_nodeinfo_in_db(info)
if print_node_info:
print("")
print("NodeInfo:")
print(info)
except Exception as e:
print(f"*** NODEINFO_APP: {str(e)}")
elif mp.decoded.portnum == portnums_pb2.POSITION_APP:
pos = mesh_pb2.Position()
try:
pos.ParseFromString(mp.decoded.payload)
if record_locations:
maybe_store_position_in_db(getattr(mp, "from"), pos, getattr(mp, "rx_rssi"))
except Exception as e:
print(f"*** POSITION_APP: {str(e)}")
elif mp.decoded.portnum == portnums_pb2.TELEMETRY_APP:
env = telemetry_pb2.Telemetry()
try:
env.ParseFromString(mp.decoded.payload)
except Exception as e:
print(f"*** TELEMETRY_APP: {str(e)}")
rssi = getattr(mp, "rx_rssi")
# Device Metrics
device_metrics_dict = {
'Battery Level': env.device_metrics.battery_level,
'Voltage': round(env.device_metrics.voltage, 2),
'Channel Utilization': round(env.device_metrics.channel_utilization, 1),
'Air Utilization': round(env.device_metrics.air_util_tx, 1)
}
if rssi:
device_metrics_dict["RSSI"] = rssi
# Environment Metrics
environment_metrics_dict = {
'Temp': round(env.environment_metrics.temperature, 2),
'Humidity': round(env.environment_metrics.relative_humidity, 0),
'Pressure': round(env.environment_metrics.barometric_pressure, 2),
'Gas Resistance': round(env.environment_metrics.gas_resistance, 2)
}
if rssi:
environment_metrics_dict["RSSI"] = rssi
# Power Metrics
# TODO
# Air Quality Metrics
# TODO
if print_telemetry:
device_metrics_string = "From: " + get_name_by_id("short", getattr(mp, "from")) + ", "
environment_metrics_string = "From: " + get_name_by_id("short", getattr(mp, "from")) + ", "
# Only use metrics that are non-zero
has_device_metrics = True
has_environment_metrics = True
has_device_metrics = all(value != 0 for value in device_metrics_dict.values())
has_environment_metrics = all(value != 0 for value in environment_metrics_dict.values())
# Loop through the dictionary and append non-empty values to the string
for label, value in device_metrics_dict.items():
if value is not None:
device_metrics_string += f"{label}: {value}, "
for label, value in environment_metrics_dict.items():
if value is not None:
environment_metrics_string += f"{label}: {value}, "
# Remove the trailing comma and space
device_metrics_string = device_metrics_string.rstrip(", ")
environment_metrics_string = environment_metrics_string.rstrip(", ")
# Print or use the final string
if has_device_metrics:
print(device_metrics_string)
if has_environment_metrics:
print(environment_metrics_string)
elif mp.decoded.portnum == portnums_pb2.TRACEROUTE_APP:
if mp.decoded.payload:
routeDiscovery = mesh_pb2.RouteDiscovery()
routeDiscovery.ParseFromString(mp.decoded.payload)
try:
route_string = " > ".join(get_name_by_id("long", node) for node in routeDiscovery.route) if routeDiscovery.route else ""
routeBack_string = " > ".join(get_name_by_id("long", node) for node in routeDiscovery.route_back) if routeDiscovery.route_back else ""
to_node = get_name_by_id("long", getattr(mp, 'to'))
from_node = get_name_by_id("long", getattr(mp, 'from'))
# Build the message without redundant arrows
routes = [to_node]
if routeBack_string:
routes.append(route_string)
routes.append(from_node)
if route_string:
routes.append(routeBack_string)
routes.append(to_node)
final_route = " > ".join(routes)
message = f"{format_time(current_time())} >>> Route: {final_route}"
# Only display traceroutes originating from yourself
if getattr(mp, 'to') == int(node_number_entry.get()):
update_gui(message, tag="info")
except AttributeError as e:
print(f"Error accessing route: {e}")
except Exception as ex:
print(f"Unexpected error: {ex}")
def decode_encrypted(mp):
"""Decrypt a meshtastic message."""
try:
# Convert key to bytes
key_bytes = base64.b64decode(key.encode('ascii'))
nonce_packet_id = getattr(mp, "id").to_bytes(8, "little")
nonce_from_node = getattr(mp, "from").to_bytes(8, "little")
# Put both parts into a single byte array.
nonce = nonce_packet_id + nonce_from_node
cipher = Cipher(algorithms.AES(key_bytes), modes.CTR(nonce), backend=default_backend())
decryptor = cipher.decryptor()
decrypted_bytes = decryptor.update(getattr(mp, "encrypted")) + decryptor.finalize()
data = mesh_pb2.Data()
data.ParseFromString(decrypted_bytes)
mp.decoded.CopyFrom(data)
except Exception as e:
if print_message_packet:
print(f"failed to decrypt: \n{mp}")
if debug:
print(f"*** Decryption failed: {str(e)}")
def process_message(mp, text_payload, is_encrypted):
"""Process a single meshtastic text message."""
if debug:
print("process_message")
if not message_exists(mp):
from_node = getattr(mp, "from")
to_node = getattr(mp, "to")
# Needed for ACK
message_id = getattr(mp, "id")
want_ack: bool = getattr(mp, "want_ack")
sender_short_name = get_name_by_id("short", from_node)
receiver_short_name = get_name_by_id("short", to_node)
display_str = ""
private_dm = False
if to_node == node_number:
display_str = f"{format_time(current_time())} DM from {sender_short_name}: {text_payload}"
if display_dm_emoji:
display_str = display_str[:9] + dm_emoji + display_str[9:]
if want_ack is True:
send_ack(from_node, message_id)
elif from_node == node_number and to_node != BROADCAST_NUM:
display_str = f"{format_time(current_time())} DM to {receiver_short_name}: {text_payload}"
elif from_node != node_number and to_node != BROADCAST_NUM:
if display_private_dms:
display_str = f"{format_time(current_time())} DM from {sender_short_name} to {receiver_short_name}: {text_payload}"
if display_dm_emoji:
display_str = display_str[:9] + dm_emoji + display_str[9:]
else:
if debug:
print("Private DM Ignored")
private_dm = True
else:
display_str = f"{format_time(current_time())} {sender_short_name}: {text_payload}"
if is_encrypted and not private_dm:
color="encrypted"
if display_encrypted_emoji:
display_str = display_str[:9] + encrypted_emoji + display_str[9:]
else:
color="unencrypted"
if not private_dm:
update_gui(display_str, text_widget=message_history, tag=color)
m_id = getattr(mp, "id")
insert_message_to_db(current_time(), sender_short_name, text_payload, m_id, is_encrypted)
text = {
"message": text_payload,
"from": getattr(mp, "from"),
"id": getattr(mp, "id"),
"to": getattr(mp, "to")
}
rssi = getattr(mp, "rx_rssi")
if rssi:
text["RSSI"] = rssi
if print_text_message:
print("")
print(text)
else:
if debug:
print("duplicate message ignored")
def message_exists(mp) -> bool:
"""Check for message id in db, ignore duplicates."""
if debug:
print("message_exists")
try:
table_name = sanitize_string(mqtt_broker) + "_" + sanitize_string(root_topic) + sanitize_string(channel) + "_messages"
with sqlite3.connect(db_file_path) as db_connection:
db_cursor = db_connection.cursor()
# Check if a record with the same message_id already exists
existing_record = db_cursor.execute(f'SELECT * FROM {table_name} WHERE message_id=?', (str(getattr(mp, "id")),)).fetchone()
return existing_record is not None
except sqlite3.Error as e:
print(f"SQLite error in message_exists: {e}")
finally:
db_connection.close()
return False
#################################
# Send Messages
def direct_message(destination_id):
"""Send a direct message."""
if debug:
print("direct_message")
if destination_id:
try:
destination_id = int(destination_id[1:], 16)
publish_message(destination_id)
except Exception as e:
if debug:
print(f"Error converting destination_id: {e}")
def publish_message(destination_id):
"""?"""
if debug:
print("publish_message")
if not client.is_connected():
connect_mqtt()
message_text = message_entry.get()
if message_text:
encoded_message = mesh_pb2.Data()
encoded_message.portnum = portnums_pb2.TEXT_MESSAGE_APP
encoded_message.payload = message_text.encode("utf-8")
generate_mesh_packet(destination_id, encoded_message)
message_entry.delete(0, 'end')
#else:
# return
def send_traceroute(destination_id):
"""Send traceroute request to destination_id."""
if debug:
print("send_TraceRoute")
if not client.is_connected():
message = format_time(current_time()) + " >>> Connect to a broker before sending traceroute"
update_gui(message, tag="info")
else:
message = format_time(current_time()) + " >>> Sending Traceroute Packet"
update_gui(message, tag="info")
if debug:
print(f"Sending Traceroute Packet to {str(destination_id)}")
encoded_message = mesh_pb2.Data()
encoded_message.portnum = portnums_pb2.TRACEROUTE_APP
encoded_message.want_response = True
destination_id = int(destination_id[1:], 16)
generate_mesh_packet(destination_id, encoded_message)
def send_node_info(destination_id, want_response):
"""Send my node information to the specified destination."""
global node_number
if debug:
print("send_node_info")
if not client.is_connected():
message = format_time(current_time()) + " >>> Connect to a broker before sending nodeinfo"
update_gui(message, tag="info")
else:
if not move_text_up(): # copy ID to Number and test for 8 bit hex
return
if destination_id == BROADCAST_NUM:
message = format_time(current_time()) + " >>> Broadcast NodeInfo Packet"
update_gui(message, tag="info")
else:
if debug:
print(f"Sending NodeInfo Packet to {str(destination_id)}")
node_number = int(node_number_entry.get())
decoded_client_id = bytes(node_name, "utf-8")
decoded_client_long = bytes(long_name_entry.get(), "utf-8")
decoded_client_short = bytes(short_name_entry.get(), "utf-8")
decoded_client_hw_model = client_hw_model
user_payload = mesh_pb2.User()
setattr(user_payload, "id", decoded_client_id)
setattr(user_payload, "long_name", decoded_client_long)
setattr(user_payload, "short_name", decoded_client_short)
setattr(user_payload, "hw_model", decoded_client_hw_model)
user_payload = user_payload.SerializeToString()
encoded_message = mesh_pb2.Data()
encoded_message.portnum = portnums_pb2.NODEINFO_APP
encoded_message.payload = user_payload
encoded_message.want_response = want_response # Request NodeInfo back
# print(encoded_message)
generate_mesh_packet(destination_id, encoded_message)
def send_position(destination_id) -> None:
"""Send current position to destination_id (which can be a broadcast.)"""
global node_number
if debug:
print("send_Position")
if not client.is_connected():
message = format_time(current_time()) + " >>> Connect to a broker before sending position"
update_gui(message, tag="info")
else:
if destination_id == BROADCAST_NUM:
message = format_time(current_time()) + " >>> Broadcast Position Packet"
update_gui(message, tag="info")
else:
if debug:
print(f"Sending Position Packet to {str(destination_id)}")
node_number = int(node_number_entry.get())
pos_time = int(time.time())
latitude_str = lat_entry.get()
longitude_str = lon_entry.get()
try:
latitude = float(latitude_str) # Convert latitude to a float
except ValueError:
latitude = 0.0
try:
longitude = float(longitude_str) # Convert longitude to a float
except ValueError:
longitude = 0.0
latitude = latitude * 1e7
longitude = longitude * 1e7
latitude_i = int(latitude)
longitude_i = int(longitude)
altitude_str = alt_entry.get()
altitude_units = 1 / 3.28084 if 'ft' in altitude_str else 1.0
altitude_number_of_units = float(re.sub('[^0-9.]','', altitude_str))
altitude_i = int(altitude_units * altitude_number_of_units) # meters
position_payload = mesh_pb2.Position()
setattr(position_payload, "latitude_i", latitude_i)
setattr(position_payload, "longitude_i", longitude_i)
setattr(position_payload, "altitude", altitude_i)
setattr(position_payload, "time", pos_time)
position_payload = position_payload.SerializeToString()
encoded_message = mesh_pb2.Data()
encoded_message.portnum = portnums_pb2.POSITION_APP
encoded_message.payload = position_payload
encoded_message.want_response = True
generate_mesh_packet(destination_id, encoded_message)
def generate_mesh_packet(destination_id, encoded_message):
"""Send a packet out over the mesh."""
global global_message_id
mesh_packet = mesh_pb2.MeshPacket()
# Use the global message ID and increment it for the next call
mesh_packet.id = global_message_id
global_message_id += 1
setattr(mesh_packet, "from", node_number)
mesh_packet.to = destination_id
mesh_packet.want_ack = False
mesh_packet.channel = generate_hash(channel, key)
mesh_packet.hop_limit = 3
if key == "":
mesh_packet.decoded.CopyFrom(encoded_message)
if debug:
print("key is none")
else:
mesh_packet.encrypted = encrypt_message(channel, key, mesh_packet, encoded_message)
if debug:
print("key present")
service_envelope = mqtt_pb2.ServiceEnvelope()
service_envelope.packet.CopyFrom(mesh_packet)
service_envelope.channel_id = channel
service_envelope.gateway_id = node_name
# print (service_envelope)
payload = service_envelope.SerializeToString()
set_topic()
# print(payload)
client.publish(publish_topic, payload)
def encrypt_message(channel, key, mesh_packet, encoded_message):
"""Encrypt a message."""
if debug:
print("encrypt_message")
if key == "AQ==":
key = "1PG7OiApB1nwvP+rz05pAQ=="
mesh_packet.channel = generate_hash(channel, key)
key_bytes = base64.b64decode(key.encode('ascii'))
# print (f"id = {mesh_packet.id}")
nonce_packet_id = mesh_packet.id.to_bytes(8, "little")
nonce_from_node = node_number.to_bytes(8, "little")
# Put both parts into a single byte array.
nonce = nonce_packet_id + nonce_from_node
cipher = Cipher(algorithms.AES(key_bytes), modes.CTR(nonce), backend=default_backend())
encryptor = cipher.encryptor()
encrypted_bytes = encryptor.update(encoded_message.SerializeToString()) + encryptor.finalize()
return encrypted_bytes
def send_ack(destination_id, message_id):
"Return a meshtastic acknowledgement."""
if debug:
print("Sending ACK")
encoded_message = mesh_pb2.Data()
encoded_message.portnum = portnums_pb2.ROUTING_APP
encoded_message.request_id = message_id
encoded_message.payload = b"\030\000"
generate_mesh_packet(destination_id, encoded_message)
#################################
# Database Handling
# Create database table for NodeDB & Messages
def setup_db():
"""Create the initial database and the nodeinfo, messages, and positions tables in it."""
if debug:
print("setup_db")
with sqlite3.connect(db_file_path) as db_connection:
db_cursor = db_connection.cursor()
# Create the nodeinfo table for storing nodeinfos
table_name = sanitize_string(mqtt_broker) + "_" + sanitize_string(root_topic) + sanitize_string(channel) + "_nodeinfo"
query = f'CREATE TABLE IF NOT EXISTS {table_name} (user_id TEXT, long_name TEXT, short_name TEXT)'
db_cursor.execute(query)
# Create the messages table for storing messages
table_name = sanitize_string(mqtt_broker) + "_" + sanitize_string(root_topic) + sanitize_string(channel) + "_messages"
query = f'CREATE TABLE IF NOT EXISTS {table_name} (timestamp TEXT,sender TEXT,content TEXT,message_id TEXT, is_encrypted INTEGER)'
db_cursor.execute(query)
# Create the positions new table for storing positions
table_name = sanitize_string(mqtt_broker) + "_" + sanitize_string(root_topic) + sanitize_string(channel) + "_positions"
query = f'CREATE TABLE IF NOT EXISTS {table_name} (node_id TEXT,short_name TEXT,timestamp TEXT,latitude REAL,longitude REAL)'
db_cursor.execute(query)
db_connection.commit()
db_connection.close()
def maybe_store_nodeinfo_in_db(info):
"""Save nodeinfo in sqlite unless that record is already there."""
if debug:
print("node info packet received: Checking for existing entry in DB")
table_name = sanitize_string(mqtt_broker) + "_" + sanitize_string(root_topic) + sanitize_string(channel) + "_nodeinfo"
try:
with sqlite3.connect(db_file_path) as db_connection:
db_cursor = db_connection.cursor()
# Check if a record with the same user_id already exists
existing_record = db_cursor.execute(f'SELECT * FROM {table_name} WHERE user_id=?', (info.id,)).fetchone()
if existing_record is None:
if debug:
print("no record found, adding node to db")
# No existing record, insert the new record
db_cursor.execute(f'''
INSERT INTO {table_name} (user_id, long_name, short_name)
VALUES (?, ?, ?)
''', (info.id, info.long_name, info.short_name))
db_connection.commit()
# Fetch the new record
new_record = db_cursor.execute(f'SELECT * FROM {table_name} WHERE user_id=?', (info.id,)).fetchone()
# Display the new record in the nodeinfo_window widget
message = f"{new_record[0]}, {new_record[1]}, {new_record[2]}"
update_gui(message, text_widget=nodeinfo_window)
else:
# Check if long_name or short_name is different, update if necessary
if existing_record[1] != info.long_name or existing_record[2] != info.short_name:
if debug:
print("updating existing record in db")
db_cursor.execute(f'''
UPDATE {table_name}
SET long_name=?, short_name=?
WHERE user_id=?
''', (info.long_name, info.short_name, info.id))
db_connection.commit()
# Fetch the updated record
updated_record = db_cursor.execute(f'SELECT * FROM {table_name} WHERE user_id=?', (info.id,)).fetchone()
# Display the updated record in the nodeinfo_window widget
message = f"{updated_record[0]}, {updated_record[1]}, {updated_record[2]}"
update_gui(message, text_widget=nodeinfo_window)
except sqlite3.Error as e:
print(f"SQLite error in maybe_store_nodeinfo_in_db: {e}")
finally:
db_connection.close()
def maybe_store_position_in_db(node_id, position, rssi=None):
"""Save position if we have no position for this node_id or the timestamp is newer than the record we have stored."""
# Must have at least a lat/lon
if position.latitude_i != 0 and position.longitude_i != 0:
rssi_string = ", RSSI: " + str(rssi) if rssi else ""
if print_position_report:
print("From: " + get_name_by_id("short", node_id) +
", lat: " + str(round(position.latitude_i * 1e-7, 7)) +
", lon: " + str(round(position.longitude_i * 1e-7, 7)) +
", alt: " + str(position.altitude) +
", PDOP: " + str(position.PDOP) +