-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathmeshwatch.py
executable file
·1587 lines (1162 loc) · 49.9 KB
/
meshwatch.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
#------------------------------------------------------------------------------
# __ __ _ __ __ _ _ --
# | \/ | ___ ___| |_\ \ / /_ _| |_ ___| |__ --
# | |\/| |/ _ \/ __| '_ \ \ /\ / / _` | __/ __| '_ \ --
# | | | | __/\__ \ | | \ V V / (_| | || (__| | | | --
# |_| |_|\___||___/_| |_|\_/\_/ \__,_|\__\___|_| |_| --
# --
#------------------------------------------------------------------------------
# Author: William McEvoy --
# Created: Sept 8 2021 --
# --
# Purpose: Send and receive messages from a Mesthtastic device. --
# --
# --
#------------------------------------------------------------------------------
# Sept 8, 2021 --
# - adding formatting and comments --
#------------------------------------------------------------------------------
# Sept 10, 2021 --
# - added Curses based text interface --
# - class and function was created for GPSProbe --
#------------------------------------------------------------------------------
# Sept 10, 2021 --
# - added recursive function to decode packets of packets --
#------------------------------------------------------------------------------
# Sept 26, 2021 --
# - renamed project to MeshWatch --
#------------------------------------------------------------------------------
# Oct 01, 2021 --
# - Added option to send X messages every Y seconds to all nodes for --
# tesing the mesh network --
# - node information now includes distance in meteres from basestation --
#------------------------------------------------------------------------------
# --
# Credit to other projects: --
# --
# Intercepting SIGINT and CTL-C in Curses --
# - https://gnosis.cx/publish/programming/charming_python_6.html --
# --
# Meshtastic-python --
# - https://github.com/meshtastic/Meshtastic-python --
#------------------------------------------------------------------------------
#Final Version
import meshtastic
import meshtastic.serial_interface
import meshtastic.tcp_interface
import time
from datetime import datetime
import traceback
from meshtastic.mesh_pb2 import _HARDWAREMODEL
from meshtastic.node import Node
from pubsub import pub
import argparse
import collections
import sys
import os
import math
#to help with debugging
import inspect
#to review logfiles
import subprocess
#for calculting distance
import geopy.distance
#For capturing keypresses and drawing text boxes
import curses
from curses import wrapper
from curses.textpad import Textbox, rectangle
#for capturing ctl-c
from signal import signal, SIGINT
from sys import exit
#------------------------------------------------------------------------------
# Variable Declaration --
#------------------------------------------------------------------------------
NAME = 'MeshWatch'
DESCRIPTION = "Send and recieve messages to a MeshTastic device"
DEBUG = False
parser = argparse.ArgumentParser(description=DESCRIPTION)
parser.add_argument('-s', '--send', type=str, help="send a text message")
parser.add_argument('-t', '--time', type=int, help="seconds to listen before exiting", default = 36000)
ifparser = parser.add_mutually_exclusive_group(required=False)
ifparser.add_argument('-p', '--port', type=str, help="port the Meshtastic device is connected to (e.g., /dev/ttyUSB0)")
ifparser.add_argument('-i', '--host', type=str, help="hostname/ipaddr of the device to connect to over TCP")
args = parser.parse_args()
#This will now be the default behaviour
#parser.add_argument('-r', '--receive', action='store_true', help="recieve and display messages")
#process arguments and assign values to local variables
if(args.send):
SendMessage = True
TheMessage = args.send
else:
SendMessage = False
#if(args.receive):
# ReceiveMessages = True
#else:
# ReceiveMessages = False
TimeToSleep = args.time
#------------------------------------------------------------------------------
# Initialize Curses --
#------------------------------------------------------------------------------
#Text windows
#stdscr = curses.initscr()
#hide the cursor
#curses.curs_set(0)
global PrintSleep #controls how fast the screens scroll
global OldPrintSleep #controls how fast the screens scroll
global TitleWindow
global StatusWindow
global Window1
global Window2
global Window3
global Window4
global Window5
global Window6
global Pad1
global InputMessageBox
global INputMessageWindow
global IPAddress
global Interface
global DeviceStatus
global DeviceName
global DevicePort
global PacketsReceived
global PacketsSent
global LastPacketType
global BaseLat
global BaseLon
global MacAddress
global DeviceID
global PauseOutput
global PriorityOutput
PrintSleep = 0.1
OldPrintSleep = PrintSleep
#------------------------------------------------------------------------------
# Functions / Classes --
#------------------------------------------------------------------------------
class TextWindow(object):
def __init__(self,name, rows,columns,y1,x1,y2,x2,ShowBorder,BorderColor,TitleColor):
self.name = name
self.rows = rows
self.columns = columns
self.y1 = y1
self.x1 = x1
self.y2 = y2
self.x2 = x2
self.ShowBorder = ShowBorder
self.BorderColor = BorderColor #pre defined text colors 1-7
self.TextWindow = curses.newwin(self.rows,self.columns,self.y1,self.x1)
self.CurrentRow = 1
self.StartColumn = 1
self.DisplayRows = self.rows #we will modify this later, based on if we show borders or not
self.DisplayColumns = self.columns #we will modify this later, based on if we show borders or not
self.PreviousLineText = ""
self.PreviousLineRow = 0
self.PreviousLineColor = 2
self.Title = ""
self.TitleColor = TitleColor
#If we are showing border, we only print inside the lines
if (self.ShowBorder == 'Y'):
self.CurrentRow = 1
self.StartColumn = 1
self.DisplayRows = self.rows -2 #we don't want to print over the border
self.DisplayColumns = self.columns -2 #we don't want to print over the border
self.TextWindow.attron(curses.color_pair(BorderColor))
self.TextWindow.border()
self.TextWindow.attroff(curses.color_pair(BorderColor))
self.TextWindow.refresh()
else:
self.CurrentRow = 0
self.StartColumn = 0
def ScrollPrint(self,PrintLine,Color=2,TimeStamp=False,BoldLine=True):
#print(PrintLine)
#for now the string is printed in the window and the current row is incremented
#when the counter reaches the end of the window, we will wrap around to the top
#we don't print on the window border
#make sure to pad the new string with spaces to overwrite any old text
current_time = datetime.now().strftime("%H:%M:%S")
if (TimeStamp):
PrintLine = current_time + ": {}".format(PrintLine)
#expand tabs to X spaces, pad the string with space
PrintLine = PrintLine.expandtabs(4)
#adjust strings
#Get a part of the big string that will fit in the window
PrintableString = ''
RemainingString = ''
PrintableString = PrintLine[0:self.DisplayColumns]
RemainingString = PrintLine[self.DisplayColumns+1:]
#Pad1.PadPrint("PrintLine:{}".format(PrintLine),2,TimeStamp=True)
#Pad1.PadPrint("Printable:{}".format(PrintableString),2,TimeStamp=True)
#Pad1.PadPrint("Remaining:{}".format(RemainingString),2,TimeStamp=True)
try:
while (len(PrintableString) > 0):
#padd with spaces
PrintableString = PrintableString.ljust(self.DisplayColumns,' ')
#if (self.rows == 1):
# #if you print on the last character of a window you get an error
# PrintableString = PrintableString[0:-2]
# self.TextWindow.addstr(0,0,PrintableString)
#else:
#unbold Previous line
self.TextWindow.attron(curses.color_pair(self.PreviousLineColor))
self.TextWindow.addstr(self.PreviousLineRow,self.StartColumn,self.PreviousLineText)
self.TextWindow.attroff(curses.color_pair(self.PreviousLineColor))
if (BoldLine == True):
#A_NORMAL Normal display (no highlight)
#A_STANDOUT Best highlighting mode of the terminal
#A_UNDERLINE Underlining
#A_REVERSE Reverse video
#A_BLINK Blinking
#A_DIM Half bright
#A_BOLD Extra bright or bold
#A_PROTECT Protected mode
#A_INVIS Invisible or blank mode
#A_ALTCHARSET Alternate character set
#A_CHARTEXT Bit-mask to extract a character
#COLOR_PAIR(n) Color-pair number n
#print new line in bold
self.TextWindow.attron(curses.color_pair(Color))
self.TextWindow.addstr(self.CurrentRow,self.StartColumn,PrintableString,curses.A_BOLD)
self.TextWindow.attroff(curses.color_pair(Color))
else:
#print new line in Regular
self.TextWindow.attron(curses.color_pair(Color))
self.TextWindow.addstr(self.CurrentRow,self.StartColumn,PrintableString)
self.TextWindow.attroff(curses.color_pair(Color))
self.PreviousLineText = PrintableString
self.PreviousLineColor = Color
self.PreviousLineRow = self.CurrentRow
self.CurrentRow = self.CurrentRow + 1
#Adjust strings
PrintableString = RemainingString[0:self.DisplayColumns]
RemainingString = RemainingString[self.DisplayColumns:]
if (self.CurrentRow > (self.DisplayRows)):
if (self.ShowBorder == 'Y'):
self.CurrentRow = 1
else:
self.CurrentRow = 0
#erase to end of line
#self.TextWindow.clrtoeol()
self.TextWindow.refresh()
except Exception as ErrorMessage:
TraceMessage = traceback.format_exc()
AdditionalInfo = "PrintLine: {}".format(PrintLine)
ErrorHandler(ErrorMessage,TraceMessage,AdditionalInfo)
def WindowPrint(self,y,x,PrintLine,Color=2):
#print at a specific coordinate within the window
#try:
#expand tabs to X spaces, pad the string with space then truncate
PrintLine = PrintLine.expandtabs(4)
#pad the print line with spaces then truncate at the display length
PrintLine = PrintLine.ljust(self.DisplayColumns -1)
PrintLine = PrintLine[0:self.DisplayColumns -x]
self.TextWindow.attron(curses.color_pair(Color))
self.TextWindow.addstr(y,x,PrintLine)
self.TextWindow.attroff(curses.color_pair(Color))
self.TextWindow.refresh()
#except Exception as ErrorMessage:
# TraceMessage = traceback.format_exc()
# AdditionalInfo = "PrintLine: {}".format(PrintLine)
# ErrorHandler(ErrorMessage,TraceMessage,AdditionalInfo)
def DisplayTitle(self):
#display the window title
Color = 0
Title = ''
try:
#expand tabs to X spaces, pad the string with space then truncate
Title = self.Title[0:self.DisplayColumns-3]
self.TextWindow.attron(curses.color_pair(self.TitleColor))
if (self.rows > 2):
#print new line in bold
self.TextWindow.addstr(0,2,Title)
else:
print ("ERROR - You cannot display title on a window smaller than 3 rows")
self.TextWindow.attroff(curses.color_pair(self.TitleColor))
self.TextWindow.refresh()
except Exception as ErrorMessage:
TraceMessage = traceback.format_exc()
AdditionalInfo = "Title: " + Title
ErrorHandler(ErrorMessage,TraceMessage,AdditionalInfo)
def Clear(self):
self.TextWindow.erase()
self.TextWindow.attron(curses.color_pair(self.BorderColor))
self.TextWindow.border()
self.TextWindow.attroff(curses.color_pair(self.BorderColor))
self.DisplayTitle()
#self.TextWindow.refresh()
if (self.ShowBorder == 'Y'):
self.CurrentRow = 1
self.StartColumn = 1
else:
self.CurrentRow = 0
self.StartColumn = 0
class TextPad(object):
#use this as a virtual notepad
#write a large amount of data to it, then display a section of it on the screen
#to have a border, use another window with a border
def __init__(self,name, rows,columns,y1,x1,y2,x2,ShowBorder,BorderColor):
self.name = name
self.rows = rows
self.columns = columns
self.y1 = y1 #These are coordinates for the window corners on the screen
self.x1 = x1 #These are coordinates for the window corners on the screen
self.y2 = y2 #These are coordinates for the window corners on the screen
self.x2 = x2 #These are coordinates for the window corners on the screen
self.ShowBorder = ShowBorder
self.BorderColor = BorderColor #pre defined text colors 1-7
self.TextPad = curses.newpad(self.rows,self.columns)
self.PreviousLineColor = 2
def PadPrint(self,PrintLine,Color=2,TimeStamp=False):
#print to the pad
try:
self.TextPad.idlok(1)
self.TextPad.scrollok(1)
current_time = datetime.now().strftime("%H:%M:%S")
if (TimeStamp):
PrintLine = current_time + ": " + PrintLine
#expand tabs to X spaces, pad the string with space then truncate
PrintLine = PrintLine.expandtabs(4)
PrintLine = PrintLine.ljust(self.columns,' ')
self.TextPad.attron(curses.color_pair(Color))
self.TextPad.addstr(PrintLine)
self.TextPad.attroff(curses.color_pair(Color))
#We will refresh after a series of calls instead of every update
self.TextPad.refresh(0,0,self.y1,self.x1,self.y1 + self.rows,self.x1 + self.columns)
except Exception as ErrorMessage:
time.sleep(2)
TraceMessage = traceback.format_exc()
AdditionalInfo = "PrintLine: " + PrintLine
ErrorHandler(ErrorMessage,TraceMessage,AdditionalInfo)
def Clear(self):
try:
self.TextPad.erase()
#self.TextPad.noutrefresh(0,0,self.y1,self.x1,self.y1 + self.rows,self.x1 + self.columns)
self.TextPad.refresh(0,0,self.y1,self.x1,self.y1 + self.rows,self.x1 + self.columns)
except Exception as ErrorMessage:
TraceMessage = traceback.format_exc()
AdditionalInfo = "erasing textpad"
ErrorHandler(ErrorMessage,TraceMessage,AdditionalInfo)
def ErrorHandler(ErrorMessage,TraceMessage,AdditionalInfo):
#Window2.ScrollPrint('ErrorHandler',10,TimeStamp=True)
#Window4.ScrollPrint('** Just a moment...**',8)
CallingFunction = inspect.stack()[1][3]
FinalCleanup(stdscr)
print("")
print("")
print("--------------------------------------------------------------")
print("ERROR - Function (",CallingFunction, ") has encountered an error. ")
print(ErrorMessage)
print("")
print("")
print("TRACE")
print(TraceMessage)
print("")
print("")
if (AdditionalInfo != ""):
print("Additonal info:",AdditionalInfo)
print("")
print("")
print("--------------------------------------------------------------")
print("")
print("")
time.sleep(1)
sys.exit('Good by for now...')
def FinalCleanup(stdscr):
stdscr.keypad(0)
curses.echo()
curses.nocbreak()
curses.curs_set(1)
curses.endwin()
#--------------------------------------
# Initialize Text window / pads --
#--------------------------------------
def CreateTextWindows():
global StatusWindow
global TitleWindow
global Window1
global Window2
global Window3
global Window4
global Window5
global HelpWindow
global Pad1
global SendMessageWindow
global InputMessageWindow
global InputMessageBox
#Colors are numbered, and start_color() initializes 8
#basic colors when it activates color mode.
#They are: 0:black, 1:red, 2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, and 7:white.
#The curses module defines named constants for each of these colors: curses.COLOR_BLACK, curses.COLOR_RED, and so forth.
#Future Note for pads: call noutrefresh() on a number of windows to update the data structure, and then call doupdate() to update the screen.
#Text windows
stdscr.nodelay (1) # doesn't keep waiting for a key press
curses.start_color()
curses.noecho()
#We do a quick check to prevent the screen boxes from being erased. Weird, I know. Could not find
#a solution. Am happy with this work around.
c = str(stdscr.getch())
#NOTE: When making changes, be very careful. Each Window's position is relative to the other ones on the same
#horizontal level. Change one setting at a time and see how it looks on your screen
#Window1 Coordinates (info window)
Window1Height = 12
Window1Length = 40
Window1x1 = 0
Window1y1 = 1
Window1x2 = Window1x1 + Window1Length
Window1y2 = Window1y1 + Window1Height
#Window2 Coordinates (small debug window)
Window2Height = 12
Window2Length = 46
Window2x1 = Window1x2 + 1
Window2y1 = 1
Window2x2 = Window2x1 + Window2Length
Window2y2 = Window2y1 + Window2Height
#Window3 Coordinates (Messages)
Window3Height = 12
Window3Length = 104
Window3x1 = Window2x2 + 1
Window3y1 = 1
Window3x2 = Window3x1 + Window3Length
Window3y2 = Window3y1 + Window3Height
#Window4 Coordinates (packet data)
Window4Height = 45
#Window4Length = Window1Length + Window2Length + Window3Length + 2
Window4Length = 60
Window4x1 = 0
Window4y1 = Window1y2
Window4x2 = Window4x1 + Window4Length
Window4y2 = Window4y1 + Window4Height
#We are going to put a window here as a border, but have the pad
#displayed inside
#Window5 Coordinates (to the right of window4)
Window5Height = 45
Window5Length = 95
Window5x1 = Window4x2 + 1
Window5y1 = Window4y1
Window5x2 = Window5x1 + Window5Length
Window5y2 = Window5y1 + Window5Height
# Coordinates (scrolling pad/window for showing keys being decoded)
Pad1Columns = Window5Length -2
Pad1Lines = Window5Height -2
Pad1x1 = Window5x1+1
Pad1y1 = Window5y1+1
Pad1x2 = Window5x2 -1
Pad1y2 = Window5y2 -1
#Help Window
HelpWindowHeight = 11
HelpWindowLength = 35
HelpWindowx1 = Window5x2 + 1
HelpWindowy1 = Window5y1
HelpWindowx2 = HelpWindowx1 + HelpWindowLength
HelpWindowy2 = HelpWindowy1 + HelpWindowHeight
#SendMessage Window
#This window will be used to display the border
#and title and will surround the input window
SendMessageWindowHeight = 6
SendMessageWindowLength = 35
SendMessageWindowx1 = Window5x2 + 1
SendMessageWindowy1 = HelpWindowy1 + HelpWindowHeight
SendMessageWindowx2 = SendMessageWindowx1 + SendMessageWindowLength
SendMessageWindowy2 = SendMessageWindowy1 + SendMessageWindowHeight
#InputMessage Window
#This window will be used get the text to be sent
InputMessageWindowHeight = SendMessageWindowHeight -2
InputMessageWindowLength = SendMessageWindowLength -2
InputMessageWindowx1 = Window5x2 + 2
InputMessageWindowy1 = HelpWindowy1 + HelpWindowHeight +1
InputMessageWindowx2 = InputMessageWindowx1 + InputMessageWindowLength -2
InputMessageWindowy2 = InputMessageWindowy1 + InputMessageWindowHeight -2
try:
#stdscr.clear()
curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK)
curses.init_pair(3, curses.COLOR_YELLOW, curses.COLOR_BLACK)
curses.init_pair(4, curses.COLOR_BLUE, curses.COLOR_BLACK)
curses.init_pair(5, curses.COLOR_MAGENTA, curses.COLOR_BLACK)
curses.init_pair(6, curses.COLOR_CYAN, curses.COLOR_BLACK)
curses.init_pair(7, curses.COLOR_WHITE, curses.COLOR_BLACK)
#--------------------------------------
# Draw Screen --
#--------------------------------------
# Create windows
# name, rows, columns, y1, x1, y2, x2,ShowBorder,BorderColor,TitleColor):
TitleWindow = TextWindow('TitleWindow',1,50,0,0,0,50,'N',0,0)
StatusWindow = TextWindow('StatusWindow',1,50,0,51,0,100,'N',0,0)
StatusWindow2 = TextWindow('StatusWindow2',1,30,0,101,0,130,'N',0,0)
Window1 = TextWindow('Window1',Window1Height,Window1Length,Window1y1,Window1x1,Window1y2,Window1x2,'Y',2,2)
Window2 = TextWindow('Window2',Window2Height,Window2Length,Window2y1,Window2x1,Window2y2,Window2x2,'Y',2,2)
Window3 = TextWindow('Window3',Window3Height,Window3Length,Window3y1,Window3x1,Window3y2,Window3x2,'Y',3,3)
Window4 = TextWindow('Window4',Window4Height,Window4Length,Window4y1,Window4x1,Window4y2,Window4x2,'Y',5,5)
Window5 = TextWindow('Window5',Window5Height,Window5Length,Window5y1,Window5x1,Window5y2,Window5x2,'Y',6,6)
HelpWindow = TextWindow('HelpWindow',HelpWindowHeight,HelpWindowLength,HelpWindowy1,HelpWindowx1,HelpWindowy2,HelpWindowx2,'Y',7,7)
SendMessageWindow = TextWindow('SendMessageWindow',SendMessageWindowHeight,SendMessageWindowLength,SendMessageWindowy1,SendMessageWindowx1,SendMessageWindowy2,SendMessageWindowx2,'Y',7,7)
InputMessageWindow = TextWindow('InputMessageWindow',InputMessageWindowHeight,InputMessageWindowLength,InputMessageWindowy1,InputMessageWindowx1,InputMessageWindowy2,InputMessageWindowx2,'N',7,7)
Pad1 = TextPad('Pad1', Pad1Lines,Pad1Columns,Pad1y1,Pad1x1,Pad1y2,Pad1x2,'N',5)
# Display the title
#StatusWindow.ScrollPrint("Preparing devices",6)
#Window1.ScrollPrint("Channel Info",2)
#Window2.ScrollPrint("Debug Info",2)
#Window3.ScrollPrint("Alerts",2)
#Window4.ScrollPrint("Details",2)
#each title needs to be initialized or you get errors in scrollprint
TitleWindow.Title, TitleWindow.TitleColor = "--MeshWatch 1.0--",2
StatusWindow.Title, StatusWindow.TitleColor = "",2
StatusWindow2.Title, StatusWindow2.TitleColor = "",2
Window1.Title, Window1.TitleColor = "Device Info",2
Window2.Title, Window2.TitleColor = "Debug",2
Window3.Title, Window3.TitleColor = "Messages",3
Window4.Title, Window4.TitleColor = "Data Packets",5
Window5.Title, Window5.TitleColor = "Extended Information",6
HelpWindow.Title, HelpWindow.TitleColor = "Help",7
SendMessageWindow.Title, SendMessageWindow.TitleColor = "Press S to send a message",7
TitleWindow.WindowPrint(0,0,TitleWindow.Title)
Window1.DisplayTitle()
Window2.DisplayTitle()
Window3.DisplayTitle()
Window4.DisplayTitle()
Window5.DisplayTitle()
HelpWindow.DisplayTitle()
SendMessageWindow.DisplayTitle()
DisplayHelpInfo()
#Prepare edit window for send message
InputMessageBox = Textbox(InputMessageWindow.TextWindow)
#NORTE: we don't need this anymore, as the SendMessageWindow has replaced it
#draw a box around the editwindow
#Upper left corner coordinates, lower right coordinate
#rectangle(stdscr, SendMessageWindowy1-1, SendMessageWindowx1-1, SendMessageWindowy2+1, SendMessageWindowx2+1)
#stdscr.addstr(SendMessageWindowy1-1, SendMessageWindowx1+1, "Enter message: (hit Ctrl-G to send)",curses.color_pair(7))
#stdscr.refresh()
except Exception as ErrorMessage:
TraceMessage = traceback.format_exc()
AdditionalInfo = "Creating text windows"
ErrorHandler(ErrorMessage,TraceMessage,AdditionalInfo)
#--------------------------------------
# Meshtastic functions --
#--------------------------------------
def fromStr(valstr):
"""try to parse as int, float or bool (and fallback to a string as last resort)
Returns: an int, bool, float, str or byte array (for strings of hex digits)
Args:
valstr (string): A user provided string
"""
if(len(valstr) == 0): # Treat an emptystring as an empty bytes
val = bytes()
elif(valstr.startswith('0x')):
# if needed convert to string with asBytes.decode('utf-8')
val = bytes.fromhex(valstr[2:])
elif valstr == True:
val = True
elif valstr == False:
val = False
else:
try:
val = int(valstr)
except ValueError:
try:
val = float(valstr)
except ValueError:
val = valstr # Not a float or an int, assume string
return val
def DecodePacket(PacketParent,Packet,Filler,FillerChar,PrintSleep=0):
global DeviceStatus
global DeviceName
global DevicePort
global PacketsReceived
global PacketsSent
global LastPacketType
global HardwareModel
global DeviceID
#This is a recursive funtion that will decode a packet (get key/value pairs from a dictionary )
#if the value is itself a dictionary, recurse
Window2.ScrollPrint("DecodePacket",2,TimeStamp=True)
#Filler = ('-' * len(inspect.stack(0)))
#used to indent packets
if (PacketParent.upper() != 'MAINPACKET'):
Filler = Filler + FillerChar
Window4.ScrollPrint("{}".format(PacketParent).upper(),2)
UpdateStatusWindow(NewLastPacketType=PacketParent)
#adjust the input to slow down the output for that cool retro feel
if (PrintSleep > 0):
time.sleep(PrintSleep)
if PriorityOutput == True:
time.sleep(5)
#if the packet is a dictionary, decode it
if isinstance(Packet, collections.abc.Mapping):
for Key in Packet.keys():
Value = Packet.get(Key)
if (PrintSleep > 0):
time.sleep(PrintSleep)
#Pad1.PadPrint("{} - {}".format(PacketParent,Key),2)
#if the value paired with this key is another dictionary, keep digging
if isinstance(Value, collections.abc.Mapping):
#Print the name/type of the packet
Window4.ScrollPrint(" ",2)
#Window4.ScrollPrint("{}".format(Key).upper(),2)
LastPacketType = Key.upper()
DecodePacket("{}/{}".format(PacketParent,Key).upper(),Value,Filler,FillerChar,PrintSleep=PrintSleep)
else:
#Print KEY if not RAW (gotta decode those further, or ignore)
if(Key == 'raw'):
Window4.ScrollPrint("{} RAW value not yet suported by DecodePacket function".format(Filler),2)
else:
Window4.ScrollPrint(" {}{}: {}".format(Filler,Key,Value),2)
else:
Window2.ScrollPrint("Warning: Not a packet!",5,TimeStamp=True)
#Window4.ScrollPrint("{}END PACKET: {} ".format(Filler,PacketParent.upper()),2)
def onReceive(packet, interface): # called when a packet arrives
global PacketsReceived
global PacketsSent
PacketsReceived = PacketsReceived + 1
Window2.ScrollPrint("onReceive",2,TimeStamp=True)
Window4.ScrollPrint(" ",2)
Window4.ScrollPrint("==Packet RECEIVED======================================",2)
Decoded = packet.get('decoded')
Message = Decoded.get('text')
To = packet.get('to')
From = packet.get('from')
#Even better method, use this recursively to decode all the packets of packets
DecodePacket('MainPacket',packet,Filler='',FillerChar='',PrintSleep=PrintSleep)
if(Message):
Window3.ScrollPrint("From: {} - {}".format(From,Message),2,TimeStamp=True)
Window4.ScrollPrint("=======================================================",2)
Window4.ScrollPrint(" ",2)
#example of scrolling the window
#Window4.TextWindow.idlok(1)
#Window4.TextWindow.scrollok(1)
#Window4.TextWindow.scroll(10)
#Window4.TextWindow.scrollok(0)
def onConnectionEstablished(interface, topic=pub.AUTO_TOPIC): # called when we (re)connect to the radio
global PriorityOutput
if(PriorityOutput == False):
#Window2.ScrollPrint('onConnectionEstablished',2,TimeStamp=True)
#Window1.WindowPrint(1,1,"Status: CONNECTED",2)
UpdateStatusWindow(NewDeviceStatus = "CONNECTED",Color=2)
From = "BaseStation"
To = "All"
current_time = datetime.now().strftime("%H:%M:%S")
Message = "MeshWatch active, please respond. [{}]".format(current_time)
Window3.ScrollPrint("From: {} - {}".format(From,Message,To),2,TimeStamp=True)
try:
interface.sendText(Message, wantAck=True)
Window4.ScrollPrint("",2)
Window4.ScrollPrint("==Packet SENT==========================================",3)
Window4.ScrollPrint("To: {}:".format(To),3)
Window4.ScrollPrint("From {}:".format(From),3)
Window4.ScrollPrint("Message {}:".format(Message),3)
Window4.ScrollPrint("=======================================================",3)
Window4.ScrollPrint("",2)
except Exception as ErrorMessage:
TraceMessage = traceback.format_exc()
AdditionalInfo = "Sending text message ({})".format(Message)
ErrorHandler(ErrorMessage,TraceMessage,AdditionalInfo)
def onConnectionLost(interface, topic=pub.AUTO_TOPIC): # called when we (re)connect to the radio
global PriorityOutput
if(PriorityOutput == False):
Window2.ScrollPrint('onConnectionLost',2,TimeStamp=True)
UpdateStatusWindow(NewDeviceStatus = "DISCONNECTED",Color=1)
def onNodeUpdated(interface, topic=pub.AUTO_TOPIC): # called when we (re)connect to the radio
global PriorityOutput
if(PriorityOutput == False):
Window2.ScrollPrint('onNodeUpdated',2,TimeStamp=True)
Window1.WindowPrint(1,4,'UPDATE RECEIVED',1,TimeStamp=True)
Window4.ScrollPrint("",2)
def SIGINT_handler(signal_received, frame):
# Handle any cleanup here
print('WARNING: Somethign bad happened. SIGINT detected.')
FinalCleanup(stdscr)
print('** END OF LINE')
sys.exit('Good by for now...')
def PollKeyboard():
global stdscr
global Window2
global interface
#Window2.ScrollPrint("PollKeyboard",2,TimeStamp=True)
ReturnChar = ""
c = ""
#curses.filter()
curses.noecho()
try:
c = chr(stdscr.getch())
except Exception as ErrorMessage:
c=""
#Look for digits (ascii 48-57 == digits 0-9)
if (c >= '0' and c <= '9'):
#print ("Digit detected")
#StatusWindow.ScrollPrint("Digit Detected",2)
ReturnChar = (c)
if (c != ""):
#print ("----------------")
#print ("Key Pressed: ",Key)
#print ("----------------")
OutputLine = "Key Pressed: " + c
#Window2.ScrollPrint(OutputLine,4)
ProcessKeypress(c)
return ReturnChar
def ProcessKeypress(Key):
global stdscr
global StatusWindow
global Window2
global Window4
global interface
global PauseOutput
global PriorityOutput
global PrintSleep
global OldPrintSleep
count = 0
OutputLine = "KEYPRESS: [" + str(Key) + "]"
Window2.ScrollPrint (OutputLine,5)
# c = clear screen
# i = get node info
# l = show system LOGS (dmesg)
# n = show all nodes in mesh
# p = pause
# q = quit
# r = reboot
# s = Send message
# T = test messages
if (Key == "p" or Key == " "):
PauseOutput = not (PauseOutput)
if (PauseOutput == True):
Window2.ScrollPrint("Pausing output",2)
StatusWindow.WindowPrint(0,0,"** Output SLOW - press SPACE again to cancel **",1)
PrintSleep = PrintSleep * 3
else:
Window2.ScrollPrint("Resuming output",2)
StatusWindow.WindowPrint(0,0," ",3)
PrintSleep = OldPrintSleep
#StatusWindow.ScrollPrint("",2)
#elif (Key == "i"):
# IPAddress = ShowIPAddress()
# ar.ShowScrollingBanner2(IPAddress,0,225,0,3,0.03)
elif (Key == "i"):
Window4.Clear()
GetMyNodeInfo(interface)
elif (Key == "l"):
Pad1.Clear()
DisplayLogs(0.01)
elif (Key == "n"):
Pad1.Clear()
DisplayNodes(interface)
elif (Key == "q"):
FinalCleanup(stdscr)
exit()
elif (Key == "c"):
ClearAllWindows()
elif (Key == "r"):
Window2.ScrollPrint('** REBOOTING **',1)