-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLoraLog.py
2679 lines (2367 loc) · 137 KB
/
LoraLog.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
# -*- coding: utf-8 -*-
import os
import time
from datetime import datetime, timedelta
from sys import exit
import asyncio
import gc
from psutil import Process
import math
from configparser import ConfigParser
from html import unescape
from pygame import mixer
# import threading
import threading
import sqlite3
# import ast
# DEBUG
# import yaml
# Tkinter imports
from PIL import Image, ImageTk
import tkinter as tk
from tkinter import ttk, Frame, Text, Label, Entry, Button, StringVar, LabelFrame, Toplevel, IntVar, BooleanVar, DoubleVar
from ctypes import windll
from customtkinter import CTk
from tkintermapview2 import TkinterMapView
import textwrap
# Meshtastic imports
from base64 import b64encode
from pubsub import pub
import meshtastic.remote_hardware
import meshtastic.version
from copy import deepcopy
import queue
message_queue = queue.Queue()
startup_complete = False
try:
from meshtastic.protobuf import config_pb2
except ImportError:
from meshtastic import config_pb2
'''
Fix sub parts if they brake a main part install > pip install --upgrade setuptools <sub tool name>
Upgrade the Meshtastic Python Library > pip install --upgrade meshtastic
Build the build > pyinstaller --icon=mesh.ico -F --onefile --noconsole LoraLog.py
can also use "pip-review --local --auto" but needs to be installed via pip install pip-review and might need multiple runs till you get Everything up-to-date
'''
# Configure Error logging
import logging
logging.basicConfig(filename='LoraLog.log', level=logging.WARN, format='%(asctime)s : %(message)s', datefmt='%m-%d %H:%M', filemode='w')
logging.error("Startin Up")
telemetry_thread = None
position_thread = None
trace_thread = None
MapMarkers = {}
ok2Send = 0
chan2send = -1
MyLora = 'ffffffff'
MyLoraID = ''
MyLora_SN = ''
MyLora_LN = ''
MyLora_Lat = -8.0
MyLora_Lon = -8.0
MyLoraText1 = ''
MyLoraText2 = ''
mylorachan = {}
tlast = int(time.time())
loop = None
pingcount = 0
incoming_uptime = 0
package_received_time = 0
zoomhome = False
ourNode = None
NIenabled = False
ThisFont = ('Fixedsys', int(10))
def showLink(event):
try:
tag_names = event.widget.tag_names("current")
idx = tag_names[0] if '#' in tag_names[1] else tag_names[1]
if '#' not in idx:
temp = type('temp', (object,), {})()
temp.data = idx
click_command(temp)
except Exception as e:
logging.error("Error in showLink: %s", str(e))
# Function to insert colored text
def insert_colored_text(text_widget, text, color, center=False, tag=None):
global MyLora
parent_frame = str(text_widget.winfo_parent())
if "frame5" not in parent_frame or "notebook" in parent_frame:
text_widget.configure(state="normal")
if color == '#d1d1d1': # and "frame3" not in parent_frame:
text_widget.insert("end", "-" * 90 + "\n", '#414141')
text_widget.tag_configure('#414141', foreground='#414141')
if tag != None: # and tag != MyLora:
text_widget.tag_configure(tag, foreground=color, underline=False)
text_widget.insert('end', text, (color, tag))
text_widget.tag_bind(tag, "<Button-1>", showLink)
else:
text_widget.insert('end', text, color)
text_widget.tag_configure(color, foreground=color)
if center:
text_widget.tag_configure("center", justify='center')
text_widget.tag_add("center", "1.0", "end")
if "!frame5" not in parent_frame or "notebook" in parent_frame:
text_widget.see('end')
text_widget.configure(state="disabled")
def add_message(nodeid, mtext, msgtime, private=False, msend='all', ackn=False, bulk=False):
global dbconnection, tabControl, text_boxes
dbcursor = dbconnection.cursor()
result = dbcursor.execute("SELECT * FROM node_info WHERE hex_id = ?", (nodeid,)).fetchone()
dbcursor.close()
if result is None:
logging.error(f"Node {nodeid} not in database")
return
msend2 = unescape(msend)
private2 = 0
if msend2 in text_boxes:
text_widget = text_boxes[msend2]
else:
text_widget = text_boxes['Direct Message']
msend2 = 'Direct Message'
private2 = 1
if bulk == False and nodeid != MyLora:
for i in range(tabControl.index("end")):
if tabControl.tab(i, "text") == msend2:
current_text = tabControl.tab(i, "text")
if '*' not in current_text:
tabControl.tab(i, text=f"{current_text} *")
label = result[5] + " (" + result[4] + ")"
tcolor = "#00c983"
if nodeid == MyLora: tcolor = "#2bd5ff"
timestamp = datetime.fromtimestamp(msgtime).strftime("%Y-%m-%d %H:%M:%S")
insert_colored_text(text_widget, "-" * 90, "#414141")
insert_colored_text(text_widget,'\n From ' + unescape(label),tcolor)
if private:
dbcursor = dbconnection.cursor()
result = dbcursor.execute("SELECT * FROM node_info WHERE hex_id = ?", (msend,)).fetchone()
dbcursor.close()
if result != None:
label = result[5] + " (" + result[4] + ")"
insert_colored_text(text_widget,' to ' + label, tcolor)
ptext = unescape(mtext).strip()
ptext = textwrap.fill(ptext, 87)
tcolor = "#d2d2d2"
if bulk == True:
tcolor = "#a1a1a1"
ptext = textwrap.indent(text=ptext, prefix=' ', predicate=lambda line: True)
insert_colored_text(text_widget, '\n' + ptext + '\n', tcolor)
insert_colored_text(text_widget,timestamp.rjust(89) + '\n', "#818181")
if bulk == False:
msend = str(msend.encode('ascii', 'xmlcharrefreplace'), 'ascii')
dbcursor = dbconnection.cursor()
dbcursor.execute("INSERT INTO chat_log (node_id, timerec, private, sendto, ackn, seen, text) VALUES (?, ?, ?, ?, ?, ? ,?)", (nodeid, msgtime, private2, msend, 0, 0, str(mtext.encode('ascii', 'xmlcharrefreplace'), 'ascii')))
dbcursor.close()
# Update chatbox if it is open
global lastchat, overlay
if len(lastchat) == 4 and overlay != None:
if lastchat[0] == nodeid or lastchat[0] == msend:
update_chat_log()
def get_messages():
with dbconnection:
dbcursor = dbconnection.cursor()
result = dbcursor.execute("SELECT * FROM chat_log ORDER BY timerec ASC").fetchall()
dbcursor.close()
for entry in result:
add_message(entry[0], unescape(entry[6]), entry[1], private=entry[2], msend=entry[3], ackn=entry[4], bulk=True)
#------------------------------------------------------------- Database Setup --------------------------------------------------------------------------
# SQLite Database
if not os.path.exists('DataBase'):
os.makedirs('DataBase')
database = 'DataBase' + os.path.sep + 'LoraLog.db3'
dbconnection = sqlite3.connect(database, timeout=250, check_same_thread=False)
dbcursor = dbconnection.cursor()
create_tmp = """CREATE TABLE IF NOT EXISTS node_info (
"node_id" integer NOT NULL PRIMARY KEY,
"timerec" TIMESTAMP,
"mac_id" text,
"hex_id" text,
"long_name" text,
"short_name" text,
"hw_model_id" text,
"is_licensed" integer DEFAULT False,
"role" integer,
"latitude" real DEFAULT -8.0,
"longitude" real DEFAULT -8.0,
"altitude" integer DEFAULT 0,
"precision_bits" integer,
"timefirst" TIMESTAMP,
"uptime" TIMESTAMP,
"ismqtt" integer DEFAULT False,
"last_snr" real DEFAULT 0.0,
"last_rssi" integer DEFAULT 0,
"last_battery" integer DEFAULT 0,
"last_voltage" real DEFAULT 0.0,
"last_sats" integer DEFAULT 0,
"ChUtil" real DEFAULT 0.0,
"AirUtilTX" real DEFAULT 0.0,
"hopstart" integer DEFAULT 0,
"distance" real DEFAULT 0.0
);"""
dbcursor.execute(create_tmp)
create_tmp = """CREATE TABLE IF NOT EXISTS naibor_info ("node_id" integer NOT NULL PRIMARY KEY, "hex_id" text, "node_pos" text, "timerec" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "timedraw" TIMESTAMP NOT NULL DEFAULT 0,"neighbor_text" text );"""
dbcursor.execute(create_tmp)
create_tmp = """CREATE TABLE IF NOT EXISTS device_metrics ("node_hex" text, "node_id" integer, "timerec" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "battery_level" integer DEFAULT 0, "voltage" real DEFAULT 0.0, "channel_utilization" real DEFAULT 0.0, "air_util_tx" real DEFAULT 0.0, "snr" real DEFAULT 0.0, "rssi" integer DEFAULT 0);"""
dbcursor.execute(create_tmp)
create_tmp = """CREATE TABLE IF NOT EXISTS environment_metrics ("node_hex" text, "node_id" integer, "timerec" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "temperature" real DEFAULT 0.0, "relative_humidity" real DEFAULT 0.0, "barometric_pressure" real DEFAULT 0.0, "gas_resistance" real DEFAULT 0.0, iaq integer DEFAULT 0);"""
dbcursor.execute(create_tmp)
create_tmp = """CREATE TABLE IF NOT EXISTS chat_log ("node_id" text, "timerec" integer, "private" integer, "sendto" text, "ackn" integer, "seen" integer, "text" text);"""
dbcursor.execute(create_tmp)
create_tmp = """CREATE TABLE IF NOT EXISTS movement_log ("node_hex" text, "node_id" integer, "timerec" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "from_latitude" real DEFAULT -8.0, "from_longitude" real DEFAULT -8.0, "from_altitude" integer DEFAULT 0, "to_latitude" real DEFAULT -8.0, "to_longitude" real DEFAULT -8.0, "to_altitude" integer DEFAULT 0);"""
dbcursor.execute(create_tmp)
dbcursor.execute("PRAGMA journal_mode=OFF")
dbcursor.connection.commit()
dbcursor.close()
def get_data_for_node(database, nodeID, days=3):
global dbconnection
cursor = dbconnection.cursor()
query = f"SELECT *, strftime('%s', timerec) as time_epoch FROM {database} WHERE node_hex = ? AND DATETIME(timerec, 'auto') > DATETIME('now', '-{days} day') ORDER BY timerec ASC"
result = cursor.execute(query, (nodeID,)).fetchall()
cursor.close()
return result
def safedatabase():
logging.error("Database saved!")
#----------------------------------------------------------- Config File Handle ------------------------------------------------------------------------
config = ConfigParser()
config['meshtastic'] = {
'interface': 'tcp',
'host': '127.0.0.1',
'serial_port': 'COM1',
'map_delete_time': '60',
'map_oldnode_time': '10080',
'map_trail_age': '12',
'metrics_age': '7',
'max_lines': '1000',
'map_tileserver': 'https://basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png',
'color_filter': 'False',
'map_cache': 'False',
'weatherbeacon': 'False',
'weatherjson': 'http://127.0.0.1/weather.json',
}
if not os.path.exists('config.ini'):
logging.error("No config file found, creating a new one")
with open('config.ini', 'w') as configfile:
config.write(configfile)
try:
config.read('config.ini')
map_delete = int(config.get('meshtastic', 'map_delete_time')) * 60
map_oldnode = int(config.get('meshtastic', 'map_oldnode_time')) * 60
map_trail_age = int(config.get('meshtastic', 'map_trail_age')) # In Hours !
metrics_age = int(config.get('meshtastic', 'metrics_age')) # In Days !
max_lines = int(config.get('meshtastic', 'max_lines')) # Max lines in log box 1 and 2
except Exception as e :
logging.error("Error loading databases: %s", str(e))
# Import the necessary module based on the interface type
if config.get('meshtastic', 'interface') == 'tcp':
import meshtastic.tcp_interface
else:
import meshtastic.serial_interface
#----------------------------------------------------------- Meshtastic Lora Con ------------------------------------------------------------------------
meshtastic_client = None
mixer.init()
sound_cache = {}
def playsound(soundfile):
if soundfile not in sound_cache:
sound_cache[soundfile] = mixer.Sound(soundfile)
sound_cache[soundfile].set_volume(0.5)
sound_cache[soundfile].play()
def value_to_graph(value, min_value=-19, max_value=1, graph_length=12):
value = max(min_value, min(max_value, value))
position = int((value - min_value) / (max_value - min_value) * (graph_length - 1))
position0 = int((0 - min_value) / (max_value - min_value) * (graph_length - 1))
graph = ['─'] * graph_length
graph[position0] = '┴'
graph[position] = '╫'
txt = "Poor"
if value > -15.0:
txt = "Fair"
if value > -7.0:
txt = "Good"
return '└' + ''.join(graph) + '┘ ' + txt
def format_number(n):
if n >= 1_000_000_000:
return f'{n // 1_000_000_000},{(n % 1_000_000_000) // 100_000_000}B'
elif n >= 1_000_000:
return f'{n // 1_000_000},{(n % 1_000_000) // 100_000}M'
# elif n >= 1_000:
# return f'{n // 1_000}K{(n % 1_000) // 100}'
else:
return f'{n:,}'
def connect_meshtastic(force_connect=False):
global meshtastic_client, MyLora, loop, isLora, MyLora_Lat, MyLora_Lon, MyLora_SN, MyLora_LN, mylorachan, chan2send, MyLoraID, zoomhome, ourNode, startup_complete
if meshtastic_client and not force_connect:
return meshtastic_client
# Initialize the event loop
try:
loop = asyncio.get_event_loop()
# loop.run_forever()
if loop.is_closed():
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
except RuntimeError:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
pub.subscribe(on_meshtastic_message, "meshtastic.receive", loop=asyncio.get_event_loop())
pub.subscribe(on_meshtastic_connection, "meshtastic.connection.established")
pub.subscribe(on_lost_meshtastic_connection,"meshtastic.connection.lost")
meshtastic_client = None
# Initialize Meshtastic interface
retry_limit = 3
attempts = 1
successful = False
target_host = config.get('meshtastic', 'host')
com_port = config.get('meshtastic', 'serial_port')
cnto = target_host
if config.get('meshtastic', 'interface') != 'tcp':
cnto = com_port
logging.debug("Connecting to meshtastic on " + cnto + "...")
insert_colored_text(text_box1, " Connecting to meshtastic on " + cnto + "...\n", "#00c983")
while not successful and attempts <= retry_limit:
try:
if config.get('meshtastic', 'interface') == 'tcp':
meshtastic_client = meshtastic.tcp_interface.TCPInterface(hostname=target_host)
else:
meshtastic_client = meshtastic.serial_interface.SerialInterface(com_port)
successful = True
isLora = True
except Exception as e:
attempts += 1
if attempts <= retry_limit:
insert_colored_text(text_box1, "[" + time.strftime("%H:%M:%S", time.localtime()) + "]", "#d1d1d1")
insert_colored_text(text_box1, " Connect re-try:" + str(e), "#db6544")
logging.error("Connect re-try: " + str(e))
time.sleep(5)
else:
logging.error("Could not connect: " + str(e))
isLora = False
return None
nodeInfo = meshtastic_client.getMyNodeInfo()
logging.error("Connected to " + nodeInfo['user']['id'] + " > " + nodeInfo['user']['shortName'] + " / " + nodeInfo['user']['longName'] + " using a " + nodeInfo['user']['hwModel'])
insert_colored_text(text_box1, " Connected to " + nodeInfo['user']['id'] + " > " + nodeInfo['user']['shortName'] + " / " + nodeInfo['user']['longName'] + " using a " + nodeInfo['user']['hwModel'] + "\n", "#00c983")
MyLoraID = nodeInfo['num']
MyLora = (nodeInfo['user']['id'])[1:]
MyLora_SN = nodeInfo['user']['shortName']
if MyLora_SN == '':
MyLora_SN = str(MyLora)[-4:]
MyLora_LN = nodeInfo['user']['longName']
print("MyLora: " + MyLora)
root.wm_title("Meshtastic Lora Logger - !" + str(MyLora).upper() + " - " + unescape(MyLora_SN))
# logLora((nodeInfo['user']['id'])[1:], ['NODEINFO_APP', nodeInfo['user']['shortName'], nodeInfo['user']['longName'], nodeInfo['user']["macaddr"],nodeInfo['user']['hwModel']])
## NEED AD MY SELF TO LOG 1ST TIME
if 'position' in nodeInfo and 'latitude' in nodeInfo['position']:
MyLora_Lat = round(nodeInfo['position']['latitude'],6)
MyLora_Lon = round(nodeInfo['position']['longitude'],6)
zoomhome = False
nodeInfo = meshtastic_client.getNode('^local')
ourNode = nodeInfo
# Lets get the Local Node's channels
lora_config = nodeInfo.localConfig.lora
modem_preset_enum = lora_config.modem_preset
modem_preset_string = config_pb2._CONFIG_LORACONFIG_MODEMPRESET.values_by_number[modem_preset_enum].name
channels = nodeInfo.channels
chan2send = 0
addtotab = False
mylorachan = {}
if channels:
for channel in channels:
addtotab = True
if len(str(channel.settings)) > 4:
psk_base64 = b64encode(channel.settings.psk).decode('utf-8')
addtotab = True
if channel.settings.name == '':
mylorachan[channel.index] = channame(modem_preset_string)
else:
mylorachan[channel.index] = channame(channel.settings.name)
if chan2send == -1:
chan2send = channel.index
# Need add to tabs for each channel
if mylorachan[channel.index] != '' and addtotab:
if mylorachan[channel.index] not in text_boxes: # Reconnected ?
insert_colored_text(text_box1, " Joined Lora Channel " + str(channel.index) + " " + mylorachan[channel.index] + " using Key " + psk_base64 + "\n", "#00c983")
tab = Frame(tabControl, background="#121212", padx=0, pady=0, borderwidth=0) # ttk.Frame(tabControl, style='TFrame', padding=0, borderwidth=0)
tab.grid_rowconfigure(0, weight=1)
tab.grid_columnconfigure(0, weight=1)
tabControl.add(tab, text=mylorachan[channel.index], padding=(0, 0, 0, 0))
text_area = Text(tab, wrap='word', width=90, height=15, bg='#242424', fg='#dddddd', font=ThisFont, undo=False, borderwidth=1, highlightthickness=0)
text_area.grid(sticky='nsew')
text_area.configure(state="disabled")
text_boxes[mylorachan[channel.index]] = text_area
if 'Direct Message' not in text_boxes:
tab = Frame(tabControl, background="#121212", padx=0, pady=0, borderwidth=0) # ttk.Frame(tabControl, style='TFrame', padding=0, borderwidth=0)
tab.grid_rowconfigure(0, weight=1)
tab.grid_columnconfigure(0, weight=1)
tabControl.add(tab, text='Direct Message', padding=(0, 0, 0, 0))
text_area = Text(tab, wrap='word', width=90, height=15, bg='#242424', fg='#dddddd', font=ThisFont, undo=False, borderwidth=1, highlightthickness=0)
text_area.grid(sticky='nsew')
text_area.configure(state="disabled")
text_boxes['Direct Message'] = text_area
time.sleep(0.5)
updatesnodes()
startup_complete = True
return meshtastic_client
def channame(s):
if '_' in s:
parts = s.lower().split('_')
return ''.join(part.capitalize() for part in parts)
return s
# Function to reset the tab's background color
def reset_tab_highlight(event):
global chan2send
selected_tab = tabControl.select()
current_text = tabControl.tab(selected_tab, "text")
if current_text.endswith(" *"):
tabControl.tab(selected_tab, text=current_text[:-2])
# the index of mylorachan[0] = 'ChanName' is the same as the channel index
chan2text = tabControl.tab(selected_tab, "text")
if chan2text != 'Direct Message':
chan2send = None
for key, value in mylorachan.items():
if value == chan2text:
chan2send = key
break
def on_lost_meshtastic_connection(interface):
global root, loop, telemetry_thread, position_thread, trace_thread, meshtastic_client, startup_complete
pub.unsubscribe(on_lost_meshtastic_connection, "meshtastic.connection.lost")
logging.error("Lost connection to Meshtastic Node.")
if telemetry_thread != None and telemetry_thread.is_alive():
telemetry_thread.join()
if position_thread != None and position_thread.is_alive():
position_thread.join()
if trace_thread != None and trace_thread.is_alive():
trace_thread.join()
pub.unsubscribe(on_meshtastic_message, "meshtastic.receive")
pub.unsubscribe(on_meshtastic_connection, "meshtastic.connection.established")
startup_complete = False
insert_colored_text(text_box1, "[" + time.strftime("%H:%M:%S", time.localtime()) + "]", "#d1d1d1")
insert_colored_text(text_box1, " Lost connection to node!, Reconnecting in 10 seconds\n", "#db6544")
try:
root.meshtastic_interface = None
meshtastic_client.close()
meshtastic_client = None
except Exception as e:
logging.error("Error closing connection: %s", str(e))
time.sleep(10)
root.meshtastic_interface = connect_meshtastic(force_connect=True)
def on_meshtastic_connection(interface, topic=pub.AUTO_TOPIC):
print("Connected to meshtastic")
def print_range(range_in_meters):
if range_in_meters < 1:
# Convert to centimeters
result = f"{range_in_meters * 100:.0f}cm"
elif range_in_meters < 1000:
# Print in meters
result = f"{range_in_meters:.0f}meter"
else:
# Convert to kilometers
result = f"{range_in_meters / 1000:.0f}km"
return result
def idToHex(nodeId):
if type(nodeId) is int:
if nodeId > 0:
in_hex = hex(nodeId)
if len(in_hex)%2: in_hex = in_hex.replace("0x","0x0") # Need account for leading zero, wish hex removes if it has one
return f"!{in_hex[2:]}"
return '!ffffffff'
def MapMarkerDelete(node_id):
global MapMarkers, mapview
if node_id in MapMarkers:
# Move Trail
if MapMarkers[node_id][4] != None:
MapMarkers[node_id][4].delete()
MapMarkers[node_id][4] = None
# Check Trail
MapMarkers[node_id][5] = 0
# Signal
if MapMarkers[node_id][6] != None:
MapMarkers[node_id][6].delete()
MapMarkers[node_id][6] = None
# Range Circle
if len(MapMarkers[node_id]) == 8:
if MapMarkers[node_id][7] != None:
MapMarkers[node_id][7].delete()
MapMarkers[node_id][7] = None
MapMarkers[node_id].pop()
# Deleting Mehard lines and Move Trail in map_widget, as we not always get all via delete up above
# Lets work the local nodes heard list
HeardDB = {}
def logheard(sourseIDx, nodeIDx, dbdata, nodesname):
global HeardDB, MapMarkers, mapview
tnow = int(time.time())
key = (sourseIDx, nodeIDx)
sourseID = idToHex(sourseIDx)[1:]
nodeID = idToHex(nodeIDx)[1:]
heard_entry = HeardDB.setdefault(key, [tnow, dbdata, None, nodesname])
heard_entry[0] = tnow
heard_entry[1] = dbdata
if sourseID in MapMarkers and nodeID in MapMarkers:
if heard_entry[2] is None:
listmaps = [MapMarkers[sourseID][0].get_position(), MapMarkers[nodeID][0].get_position() ]
heard_entry[2] = mapview.set_path(listmaps, color="#006642", width=2, name=sourseID)
# We moved need re draw
def redrawnaibors(sourceIDx):
for key, value in HeardDB.items():
if value[2] is not None and (key[0] == sourceIDx or key[1] == sourceIDx):
value[2].delete()
value[2] = None
sourseID = idToHex(key[0])[1:]
nodeID = idToHex(key[1])[1:]
if sourseID in MapMarkers and nodeID in MapMarkers:
listmaps = [MapMarkers[sourseID][0].get_position(), MapMarkers[nodeID][0].get_position()]
value[2] = mapview.set_path(listmaps, color="#006642", width=2, name=sourseID)
def deloldheard(deltime):
tnow = int(time.time())
keys_to_delete = [key for key, value in HeardDB.items() if tnow - value[0] > (deltime / 3)]
for key in keys_to_delete:
value = HeardDB[key]
if value[2] is not None:
value[2].delete()
value[2] = None
del HeardDB[key]
def adjust_rx_time(rx_time):
rx_datetime = datetime.fromtimestamp(rx_time)
current_local_time = datetime.now()
# if bigger then 6 hours or 0 then set to current time
if rx_time == 0 or abs((current_local_time - rx_datetime).total_seconds()) > 21600:
rx_datetime = current_local_time
return rx_datetime
# Lets add a small queue to handle the messages at startup, seeing we might get chat while the channels not yet loaded
def on_meshtastic_message(packet, interface, loop=None):
if not startup_complete:
message_queue.put(("meshtastic.receive", packet))
else:
while not message_queue.empty():
topic, message = message_queue.get()
if topic == "meshtastic.receive":
on_meshtastic_message2(message)
time.sleep(0.15)
on_meshtastic_message2(packet)
pass
def on_meshtastic_message2(packet):
# print(yaml.dump(packet), end='\n\n')
global MyLora, MyLoraText1, MyLoraText2, MapMarkers, dbconnection, MyLora_Lat, MyLora_Lon, incoming_uptime, package_received_time
if MyLora == '':
print('*** MyLora is empty ***\n')
# return
ischat = False
tnow = int(time.time())
text_from = ''
if 'fromId' in packet and packet['fromId'] is not None:
text_from = packet.get('fromId', '')[1:]
if text_from == '':
text_from = idToHex(packet["from"])[1:]
fromraw = text_from
fromname = text_from
viaMqtt = False
if "viaMqtt" in packet:
viaMqtt = True
nodesnr = 0
if "rxSnr" in packet and packet['rxSnr'] is not None:
nodesnr = packet['rxSnr']
else:
# Apparently chat for some odd reason does not have viaMqtt, but return no snr either
viaMqtt = True
hopStart = -1
if "hopStart" in packet:
hopStart = packet.get('hopStart', 0) - packet.get('hopLimit', 0) # packet.get('hopStart', -1)
adjusted_time = adjust_rx_time(packet.get('rx_time', 0)).strftime("%H:%M:%S")
with dbconnection:
dbcursor = dbconnection.cursor()
if text_from != '':
result = dbcursor.execute("SELECT * FROM node_info WHERE node_id = ?", (packet["from"],)).fetchone()
if result is None:
sn = str(fromraw[-4:])
ln = "Meshtastic " + sn
dbcursor.execute("INSERT INTO node_info (node_id, timerec, hex_id, ismqtt, last_snr, last_rssi, timefirst, short_name, long_name) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", (packet["from"], packet.get('rx_time', tnow), text_from, viaMqtt, nodesnr, packet.get('rxRssi', 0), tnow, sn, ln))
result = dbcursor.execute("SELECT * FROM node_info WHERE node_id = ?", (packet["from"],)).fetchone()
insert_colored_text(text_box1, "[" + adjusted_time + "] New Node Logged\n", "#d1d1d1")
insert_colored_text(text_box1, (' ' * 11) + "Node ID !" + fromraw + " (" + text_from + ")\n", "#e8643f", tag=fromraw)
playsound('Data' + os.path.sep + 'NewNode.mp3')
else:
# Added timefirst here for now to so we can sync up the 2 databases
if result[5] == '': result[5] = str(fromraw[-4:])
if result[4] == '': result[4] = "Meshtastic " + str(fromraw[-4:])
text_from = unescape(result[5]) + " (" + unescape(result[4]) + ")"
fromname = unescape(result[5])
dbcursor.execute("UPDATE node_info SET timerec = ?, ismqtt = ?, last_snr = ?, last_rssi = ?, hopstart = ? WHERE node_id = ?", (packet.get('rx_time', tnow), viaMqtt, nodesnr, packet.get('rxRssi', 0), hopStart, packet["from"]))
if "decoded" in packet:
data = packet["decoded"]
if text_from !='':
text_msgs = ''
# Lets Work the Msgs
if data["portnum"] == "ADMIN_APP":
if "getDeviceMetadataResponse" in data["admin"]:
text_raws = f"Firmware version : {data['admin']['getDeviceMetadataResponse']['firmwareVersion']}"
else:
text_raws = 'Admin Data'
elif data["portnum"] == "TELEMETRY_APP":
text_raws = 'Node Telemetry'
telemetry = packet['decoded'].get('telemetry', {})
if telemetry:
device_metrics = telemetry.get('deviceMetrics', {})
if device_metrics:
dbcursor.execute("UPDATE node_info SET last_battery = ?, last_voltage = ?, uptime = ?, ChUtil = ?, AirUtilTX = ? WHERE node_id = ?", (device_metrics.get('batteryLevel', 0), device_metrics.get('voltage', 0.00), device_metrics.get('uptimeSeconds', 0), device_metrics.get('channelUtilization', 0.00), device_metrics.get('airUtilTx', 0.00), packet["from"]))
dbcursor.execute("INSERT INTO device_metrics (node_hex, node_id, battery_level, voltage, channel_utilization, air_util_tx, snr, rssi) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", (fromraw, packet["from"], device_metrics.get('batteryLevel', 0), device_metrics.get('voltage', 0.00), device_metrics.get('channelUtilization', 0.00), device_metrics.get('airUtilTx', 0.00), packet.get('rxSnr', 0), packet.get('rxRssi', 0)))
text_raws += '\n' + (' ' * 11) + 'Battery: ' + str(device_metrics.get('batteryLevel', 0)) + '% '
text_raws += 'Power: ' + str(round(device_metrics.get('voltage', 0.00),2)) + 'v '
text_raws += 'ChUtil: ' + str(round(device_metrics.get('channelUtilization', 0.00),2)) + '% '
text_raws += 'AirUtilTX (DutyCycle): ' + str(round(device_metrics.get('airUtilTx', 0.00),2)) + '%'
if 'uptimeSeconds' in device_metrics:
text_raws += '\n' + (' ' * 11) + uptimmehuman(device_metrics.get('uptimeSeconds', 0), tnow)
if MyLora == fromraw:
MyLoraText1 = (' ChUtil').ljust(13) + str(round(device_metrics.get('channelUtilization', 0.00),2)).rjust(6) + '%\n' + (' AirUtilTX').ljust(13) + str(round(device_metrics.get('airUtilTx', 0.00),2)).rjust(6) + '%\n'
if device_metrics.get('voltage', 0.00) > 0.00: MyLoraText1 += (' Power').ljust(13) + str(round(device_metrics.get('voltage', 0.00),2)).rjust(6) + 'v\n'
if device_metrics.get('batteryLevel', 0) > 0: MyLoraText1 += (' Battery').ljust(13) + str(device_metrics.get('batteryLevel', 0)).rjust(6) + '%\n'
power_metrics = telemetry.get('powerMetrics', {})
if power_metrics:
text_raws += '\n' + (' ' * 11) + 'CH1 Voltage: ' + str(round(power_metrics.get('ch1_voltage', 'N/A'),2)) + 'v'
text_raws += ' CH1 Current: ' + str(round(power_metrics.get('ch1_current', 'N/A'),2)) + 'mA'
text_raws += ' CH2 Voltage: ' + str(round(power_metrics.get('ch2_voltage', 'N/A'),2)) + 'v'
text_raws += ' CH2 Current: ' + str(round(power_metrics.get('ch2_current', 'N/A'),2)) + 'mA'
environment_metrics = telemetry.get('environmentMetrics', {})
if environment_metrics:
dbcursor.execute("INSERT INTO environment_metrics (node_hex, node_id, temperature, relative_humidity, barometric_pressure) VALUES (?, ?, ?, ?, ?)", (fromraw, packet["from"], environment_metrics.get('temperature', 0.0), environment_metrics.get('relativeHumidity', 0.0), environment_metrics.get('barometricPressure', 0.0)))
# , environment_metrics.get('gasResistance', 0.00) ? no clue yet how metrics reports this
# , environment_metrics.get('iaq', 0) ? no clue yet how metrics reports this
# But we have in DB for now so all we need do if we do get these is add it to the insert
text_raws += '\n' + (' ' * 11) + 'Temperature: ' + str(round(environment_metrics.get('temperature', 0.0),1)) + '°C'
text_raws += ' Humidity: ' + str(round(environment_metrics.get('relativeHumidity', 0.0),1)) + '%'
text_raws += ' Pressure: ' + str(round(environment_metrics.get('barometricPressure', 0.00),2)) + 'hPa'
localstats_metrics = telemetry.get('localStats', {})
if localstats_metrics:
text_raws += '\n' + (' ' * 11) + 'PacketsTx: ' + str(localstats_metrics.get('numPacketsTx', 0))
text_raws += ' PacketsRx: ' + str(localstats_metrics.get('numPacketsRx', 0))
text_raws += ' PacketsRxBad: ' + str(localstats_metrics.get('numPacketsRxBad', 0))
if localstats_metrics.get('numRxDupe', 0) > 0:
# Number of received packets that were duplicates (due to multiple nodes relaying)
text_raws += ' RxDupe: ' + str(localstats_metrics.get('numRxDupe', 0))
if localstats_metrics.get('numTxRelay', 0) > 0:
# Number of packets we transmitted that were a relay for others (not originating from ourselves)
text_raws += '\n' + (' ' * 11) + 'TxRelay: ' + str(localstats_metrics.get('numTxRelay', 0))
if localstats_metrics.get('numTxRelayCanceled', 0) > 0:
# Number of times we canceled a packet to be relayed, because someone else did it before us
text_raws += ' TxCanceled: ' + str(localstats_metrics.get('numTxRelayCanceled', 0))
text_raws += ' Nodes: ' + str(localstats_metrics.get('numOnlineNodes', 0)) + '/' + str(localstats_metrics.get('numTotalNodes', 0))
MyLoraText2 = (' Packets Tx').ljust(13) + format_number(localstats_metrics.get('numPacketsTx', 0)).rjust(7) + '\n'
if localstats_metrics.get('numTxRelay', 0) > 0:
MyLoraText2 += (' Tx Relay').ljust(13) + format_number(localstats_metrics.get('numTxRelay', 0)).rjust(7) + '\n'
if localstats_metrics.get('numTxRelayCanceled', 0) > 0:
MyLoraText2 += (' Tx Cancel').ljust(13) + format_number(localstats_metrics.get('numTxRelayCanceled', 0)).rjust(7) + '\n'
MyLoraText2 += (' Packets Rx').ljust(13) + format_number(localstats_metrics.get('numPacketsRx', 0)).rjust(7) + '\n' + (' Rx Bad').ljust(13) + format_number(localstats_metrics.get('numPacketsRxBad', 0)).rjust(7) + '\n'
if localstats_metrics.get('numRxDupe', 0) > 0:
MyLoraText2 += (' Rx Dupe').ljust(13) + format_number(localstats_metrics.get('numRxDupe', 0)).rjust(7) + '\n'
MyLoraText2 += (' Nodes').ljust(13) + (format_number(localstats_metrics.get('numOnlineNodes', 0)) + '/' + format_number(localstats_metrics.get('numTotalNodes', 0))).rjust(7) + '\n'
if 'uptimeSeconds' in device_metrics and fromraw == MyLora:
incoming_uptime = device_metrics.get('uptimeSeconds', 0)
package_received_time = tnow
if text_raws == 'Node Telemetry':
text_raws += ' No Data'
elif data["portnum"] == "CHAT_APP" or data["portnum"] == "TEXT_MESSAGE_APP":
text = ''
if 'chat' in data:
text = data.get('chat', '')
if 'text' in data:
text = data.get('text', '')
if text != '':
text_msgs = str(text.encode('ascii', 'xmlcharrefreplace'), 'ascii').rstrip()
text_raws = text
text_chns = 'Direct Message'
if "toId" in packet and packet["toId"] == '^all' and mylorachan:
text_chns = str(mylorachan[0])
if "channel" in packet and mylorachan:
text_chns = str(mylorachan[packet["channel"]])
ischat = True
playsound('Data' + os.path.sep + 'NewChat.mp3')
else:
text_raws = 'Node Chat Encrypted'
elif data["portnum"] == "POSITION_APP":
position = data["position"]
nodelat = round(position.get('latitude', -8.0),6)
nodelon = round(position.get('longitude', -8.0),6)
nodealt = position.get('altitude', 0)
node_dist = 0.0
extra = ''
if nodelat != -8.0 and nodelon != -8.0:
if (result[9] != nodelat or result[10] != nodelon or result[11] != nodealt) and result[9] != -8.0 and result[10] != -8.0:
# We moved add to movement log ?
dbcursor.execute("INSERT INTO movement_log (node_hex, node_id, timerec, from_latitude, from_longitude, from_altitude, to_latitude, to_longitude, to_altitude) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", (fromraw, packet["from"], tnow, result[9], result[10], result[11], nodelat, nodelon, nodealt))
extra = '(Moved!) '
# MapMarkerDelete(fromraw)
if fromraw == MyLora:
MyLora_Lat = nodelat
MyLora_Lon = nodelon
else:
node_dist = calc_gc(nodelat, nodelon, MyLora_Lat, MyLora_Lon)
dbcursor.execute("UPDATE node_info SET latitude = ?, longitude = ?, altitude = ?, precision_bits = ?, last_sats = ?, distance = ? WHERE node_id = ?", (nodelat, nodelon, position.get('altitude', 0), position.get('precisionBits', 0), position.get('satsInView', 0), node_dist, packet["from"]))
text_msgs = 'Node Position '
text_msgs += 'latitude ' + str(round(nodelat,4)) + ' '
text_msgs += 'longitude ' + str(round(nodelon,4)) + ' '
text_msgs += 'altitude ' + str(nodealt) + ' meter\n' + (' ' * 11)
if nodelat != -8.0 and nodelon != -8.0:
if MyLora != fromraw and nodelat != -8.0 and nodelon != -8.0:
text_msgs += "Distance: ±" + str(node_dist) + "km "
if fromraw in MapMarkers:
if MapMarkers[fromraw][0] != None:
MapMarkers[fromraw][0].set_position(nodelat, nodelon)
MapMarkers[fromraw][0].set_text(result[5])
if MapMarkers[fromraw][6] != None:
MapMarkers[fromraw][6].set_position(nodelat, nodelon)
text_msgs += extra
if 'precisionBits' in position and position.get('precisionBits', 0) > 0:
AcMeters = round(23905787.925008 * math.pow(0.5, position.get('precisionBits', 0)), 2)
if AcMeters > 1.0:
text_msgs += '(Accuracy ±' + print_range(AcMeters) + ') '
if fromraw in MapMarkers and AcMeters >= 30.0 and AcMeters <= 5000.0:
# Lets draw only a circle if distance bigger then 30m or smaller then 5km
if len(MapMarkers[fromraw]) == 7:
MapMarkers[fromraw].append(None)
MapMarkers[fromraw][7] = mapview.set_polygon(position=(nodelat, nodelon), range_in_meters=(AcMeters * 2),fill_color="gray25")
if "satsInView" in position:
text_msgs += '(' + str(position.get('satsInView', 0)) + ' satelites)'
if extra == '(Moved!) ':
redrawnaibors(packet["from"])
text_raws = text_msgs
elif data["portnum"] == "NODEINFO_APP":
node_info = packet['decoded'].get('user', {})
if node_info:
tmp = node_info.get('shortName', str(fromraw)[:-4])
if tmp == str(fromraw)[:-4]:
if result[5] != tmp and result[5] != '':
tmp = result[5]
lora_sn = str(tmp.encode('ascii', 'xmlcharrefreplace'), 'ascii')
tmp = node_info.get('longName', 'Meshtastic ' + str(fromraw)[:-4])
if tmp == 'Meshtastic ' + str(fromraw)[:-4]:
if result[4] != tmp and result[4] != '':
tmp = result[4]
lora_ln = str(tmp.encode('ascii', 'xmlcharrefreplace'), 'ascii')
lora_mc = node_info.get('macaddr', 'N/A')
lora_mo = node_info.get('hwModel', 'N/A')
if fromraw in MapMarkers and MapMarkers[fromraw][0] != None:
MapMarkers[fromraw][0].set_text(unescape(lora_sn))
text_raws = "Node Info using hardware " + lora_mo
nodelicense = False
if 'isLicensed' in packet:
text_raws += " (Licensed)"
nodelicense = True
if 'role' in packet:
text_raws += " Role: " + node_info.get('role', 'N/A')
text_from = lora_sn + " (" + lora_ln + ")"
dbcursor.execute("UPDATE node_info SET mac_id = ?, long_name = ?, short_name = ?, hw_model_id = ?, is_licensed = ?, role = ? WHERE node_id = ?", (lora_mc, lora_ln, lora_sn, lora_mo, nodelicense, node_info.get('role', 'N/A'), packet["from"]))
else:
text_raws = 'Node Info No Data'
elif data["portnum"] == "NEIGHBORINFO_APP":
text_raws = 'Node Neighborinfo'
if fromraw not in MapMarkers:
if result[9] != -8.0 and result[10] != -8.0:
MapMarkers[fromraw] = [None, True, tnow, None, None, 0, None]
MapMarkers[fromraw][0] = mapview.set_marker(result[9], result[10], text=unescape(result[5]), icon_index=3, text_color = '#2bd5ff', font = ('Fixedsys', 8), data=fromraw, command = click_command)
if "neighborinfo" in data and "neighbors" in data["neighborinfo"]:
text = data["neighborinfo"]["neighbors"]
for neighbor in text:
nodeid = idToHex(neighbor["nodeId"])[1:]
tmp = dbcursor.execute("SELECT * FROM node_info WHERE hex_id = ? AND latitude != -8 AND longitude != -8", (nodeid,)).fetchone()
nbNide = '!' + nodeid
if tmp is not None:
nbNide = str(tmp[5].encode('ascii', 'xmlcharrefreplace'), 'ascii') # unescape(tmp[5])
if nodeid not in MapMarkers and nodeid != MyLora:
MapMarkers[nodeid] = [None, True, tnow, None, None, 0, None]
MapMarkers[nodeid][0] = mapview.set_marker(tmp[9], tmp[10], text=unescape(nbNide), icon_index=3, text_color = '#2bd5ff', font = ('Fixedsys', 8), data=nodeid, command = click_command)
dbcursor.execute("UPDATE node_info SET timerec = ? WHERE hex_id = ?", (tnow, nodeid)) # We dont need to update this as we only update if we hear it our self
nodeid = tmp[5]
else:
nodeid = '!' + nodeid
text_raws += '\n' + (' ' * 11) + nodeid
if "snr" in neighbor:
text_raws += ' (' + str(neighbor["snr"]) + 'dB)'
logheard(packet["from"], neighbor["nodeId"], neighbor.get('snr', 0.00), nbNide)
else:
text_raws += ' No Data'
elif data["portnum"] == "RANGE_TEST_APP":
text_raws = 'Node RangeTest'
payload = data.get('payload', b'')
text_raws += '\n' + (' ' * 11) + 'Payload: ' + str(payload.decode())
elif data["portnum"] == "TRACEROUTE_APP":
TraceTo = idToHex(packet['to'])
TraceTo_tx = TraceTo
TraceFrom = idToHex(packet['from'])
TraceFrom_tx = TraceFrom
result2 = dbcursor.execute("SELECT * FROM node_info WHERE hex_id = ?", (TraceTo[1:],)).fetchone()
if result2:
TraceTo_tx = result2[5]
result2 = dbcursor.execute("SELECT * FROM node_info WHERE hex_id = ?", (TraceFrom[1:],)).fetchone()
if result2:
TraceFrom_tx = result2[5]
route = packet['decoded']['traceroute'].get('route', [])
snr = packet['decoded']['traceroute'].get('snrTowards', [])
routeBack = packet['decoded']['traceroute'].get('routeBack', [])
snrBack = packet['decoded']['traceroute'].get('snrBack', [])
text_raws = 'Node Traceroute\n' + (' ' * 11) + 'From : ' + TraceTo_tx + ' --> '
index = 0
if routeBack:
for nodeuuid in routeBack:
nodeidt = idToHex(nodeuuid)[1:]
result2 = dbcursor.execute("SELECT * FROM node_info WHERE hex_id = ?", (nodeidt,)).fetchone()
if result2:
text_raws += result2[5]
else:
text_raws += '!' + nodeidt
if snrBack and snrBack[index] != -128 and snrBack[index] != 0:
text_raws += f" ({snrBack[index] / 4:.2f}dB)"
text_raws += ' --> '
index += 1
text_raws += TraceFrom_tx
if snrBack and snrBack[index] != -128 and snrBack[index] != 0:
text_raws += f" ({snrBack[index] / 4:.2f}dB)"
text_raws += '\n' + (' ' * 11) + 'Back : ' + TraceFrom_tx + ' --> '
index = 0
if route:
for nodeuuid in route:
nodeidt = idToHex(nodeuuid)[1:]
result2 = dbcursor.execute("SELECT * FROM node_info WHERE hex_id = ?", (nodeidt,)).fetchone()
if result2:
text_raws += result2[5]
else:
text_raws += '!' + nodeidt
if snr and snr[index] != -128 and snr[index] != 0:
text_raws += f" ({snr[index] / 4:.2f}dB)"
text_raws += ' --> '
index += 1
text_raws += TraceTo_tx
if snr and snr[index] != -128 and snr[index] != 0:
text_raws += f" ({snr[index] / 4:.2f}dB)"
elif data["portnum"] == "ROUTING_APP":
text_raws = 'Node Routing'
if "errorReason" in data["routing"]:
text_raws += ' - Error : ' + data["routing"]["errorReason"]
else:
if 'portnum' in data:
text_raws = 'Node ' + (data["portnum"].split('_APP', 1)[0]).title()
else:
text_raws = 'Node Unknown Packet'
# Lets work the map
if fromraw != MyLora:
if fromraw in MapMarkers:
MapMarkers[fromraw][2] = tnow
if viaMqtt == True and MapMarkers[fromraw][1] == False:
MapMarkers[fromraw][1] = True
if MapMarkers[fromraw][0] != None:
MapMarkers[fromraw][0].change_icon(3)
elif viaMqtt == False and MapMarkers[fromraw][1] == True:
MapMarkers[fromraw][1] = False
if MapMarkers[fromraw][0] != None:
MapMarkers[fromraw][0].change_icon(2)
elif result[9] != -8.0 and result[10] != -8.0 and viaMqtt == True:
MapMarkers[fromraw] = [None, True, tnow, None, None, 0, None]
MapMarkers[fromraw][0] = mapview.set_marker(result[9], result[10], text=unescape(result[5]), icon_index=3, text_color = '#2bd5ff', font = ('Fixedsys', 8), data=fromraw, command = click_command)
MapMarkers[fromraw][0].text_color = '#2bd5ff'
elif result[9] != -8.0 and result[10] != -8.0 and viaMqtt == False:
MapMarkers[fromraw] = [None, False, tnow, None, None, 0, None]
MapMarkers[fromraw][0] = mapview.set_marker(result[9], result[10], text=unescape(result[5]), icon_index=2, text_color = '#2bd5ff', font = ('Fixedsys', 8), data=fromraw, command = click_command)
MapMarkers[fromraw][0].text_color = '#2bd5ff'
# Lets add a indicator
if fromraw in MapMarkers and MapMarkers[fromraw][6] == None and 'localstats_metrics' not in packet:
MapMarkers[fromraw][6] = mapview.set_marker(result[9], result[10], icon_index=5, data=fromraw, command = click_command)
elif fromraw in MapMarkers and MapMarkers[fromraw][6] != None and 'localstats_metrics' not in packet:
MapMarkers[fromraw][6].change_icon(5)
# Cleanup and get ready to print
text_from = unescape(text_from)
text_raws = unescape(text_raws)
text_via = ''
if viaMqtt == True:
text_via = ' via mqtt'
if hopStart > 0:
text_via += ' via ' + str(hopStart) + ' node'
chantxt = (' ' * 11)
if "channel" in packet:
chantxt = ' ' + str(mylorachan[packet["channel"]])
if len(chantxt) <= 10:
chantxt += (' ' * (11 - len(chantxt)))
else:
chantxt = chantxt[:8] + '.. '
if text_raws != '' and MyLora != fromraw:
insert_colored_text(text_box1, '[' + adjusted_time + '] ' + text_from + ' [!' + fromraw + ']' + text_via + "\n", "#d1d1d1", tag=fromraw)
if ischat == True:
add_message(fromraw, text_raws, tnow, msend=text_chns)
if viaMqtt == True:
insert_colored_text(text_box1, chantxt + text_raws + '\n', "#c9a500")
else:
text_from = ''
if nodesnr != 0 and MyLora != fromraw:
if text_from == '':
text_from = '\n' + (' ' * 11)
text_from += f"{round(nodesnr,1)}dB {value_to_graph(nodesnr)}"
insert_colored_text(text_box1, chantxt + text_raws + text_from + '\n', "#00c983")
elif text_raws != '' and MyLora == fromraw:
insert_colored_text(text_box2, "[" + adjusted_time + '] ' + text_from + text_via + "\n", "#d1d1d1")
insert_colored_text(text_box2, chantxt + text_raws + '\n', "#00c983")