-
Notifications
You must be signed in to change notification settings - Fork 0
/
uart.py
executable file
·1256 lines (1194 loc) · 43.1 KB
/
uart.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
#*-------------------------------------------*#
# Title : UART Tool v1.4.3 #
# File : uart.py #
# Author : Yigit Suoglu #
# License : EUPL-1.2 #
# Last Edit : 20/12/2021 #
#*-------------------------------------------*#
# Description : Python3 script for serial #
# communication via UART #
#*-------------------------------------------*#
import sys
import serial
import threading
import time
import signal
import os
import random
from serial import Serial
from datetime import datetime
global listener_alive
global block_listener
global log_listener_check
global program_log
global log_directory
global log
global log_lock
#Prompt coloring
def get_now():
return '\033[35m' + str(datetime.now()).replace('.', ',') + ':\033[0m'
def get_time_stamp():
return '\033[F' + get_now() + ' '
def print_time_stamp():
print_raw(get_time_stamp())
def print_error(msg, write_log=True):
global log_listener_check
sys.stdout.write('\033[31m' + msg + '\033[0m')
if write_log:
log_thread = threading.Thread(target=log_write, args=[msg.strip('\n'), 'error'])
log_thread.start()
def print_fatal(msg, write_log=True):
global log_listener_check
sys.stdout.write('\033[1;31m' + msg + '\033[0m')
if write_log:
log_thread = threading.Thread(target=log_write, args=[msg.strip('\n'), 'fatal error'])
log_thread.start()
def print_success(msg, write_log=True):
global log_listener_check
sys.stdout.write('\033[32m' + msg + '\033[0m')
if write_log:
log_thread = threading.Thread(target=log_write, args=[msg.strip('\n'), 'success'])
log_thread.start()
def print_info(msg, write_log=True):
global log_listener_check
sys.stdout.write('\033[2m' + msg + '\033[0m')
if write_log:
log_thread = threading.Thread(target=log_write, args=[msg.strip('\n'), 'info'])
log_thread.start()
def print_warn(msg, write_log=True):
global log_listener_check
sys.stdout.write('\033[91m' + msg + '\033[0m')
if write_log:
log_thread = threading.Thread(target=log_write, args=[msg.strip('\n'), 'warning'])
log_thread.start()
#Helper functions
def print_raw(msg):
sys.stdout.write(msg)
def get_log_time(entry_time):
return entry_time.strftime('%Y-%m-%d %H:%M:%S,%f ')
def get_cpu_time():
return time.clock_gettime_ns(time.CLOCK_THREAD_CPUTIME_ID)
def usleep(us):
time.sleep(us/1000000.0)
def log_write(entry, entry_type=''):
global program_log
global log_lock
global log
entry_time = datetime.now()
if program_log is not None and not os.path.isfile(program_log):
program_log = None
print_raw(get_now() + ' ')
print_warn('Log is missing!\n')
if program_log is None:
return
attempts = 0
while log_lock:
if attempts == 100:
print_error('Log lock timeout!\n')
print_input_symbol()
return
attempts += 1
usleep(10)
log_lock = True
try:
if entry_type != '':
entry_type += ': '
log = open(str(program_log), 'a')
log.write(get_log_time(entry_time))
for num in range(100):
entry = entry.replace(('\033[' + str(num) + 'm'), '')
entry_list = str(entry).split('\n')
log.write(entry_type + entry_list[-1].lower() + '\n')
log.close()
except Exception as log_err:
program_log = None
print_warn('Cannot keep log\n')
print_error(str(log_err) + '\n')
print_input_symbol()
finally:
log_lock = False
def serial_write(send_data):
try:
uart_conn.write(send_data)
except Exception as serial_write_error:
print_error('Cannot send!\n')
print_error(str(serial_write_error) + '\n')
def print_input_symbol():
sys.stdout.write('\033[32m> \033[0m')
class ListenerControl(Exception):
pass
def check_listener(signum, frame):
global log_listener_check
if log_listener_check: #so that log won't be spammed with it
log_listener_check = False
msg = 'debug: listener daemon check ' + str(signum) + ' ' + str(frame)
log_thread = threading.Thread(target=log_write, args=[msg])
log_thread.start()
raise ListenerControl
def process_timeout(signum, frame):
global log_listener_check
print_fatal('Timeout!\n', False)
msg = 'fatal error: process timeout ' + str(signum) + ' ' + str(frame)
log_thread = threading.Thread(target=log_write, args=[msg, 'error'])
log_thread.start()
raise TimeoutError
def print_help():
print_raw(' \033[4mUsage\033[0m:\n')
print_raw(
' Enter a command or data to send. Commands start with \'\\\'. To send a \'\\\' as a first byte use \'\\\\\'\n')
print_raw('\n')
print_raw(' \033[4mAvailable Commands\033[0m:\n')
print_raw(' ~ \\bin : print received bytes as binary number\n')
print_raw(' ~ \\binhex : print received bytes as binary number and hexadecimal equivalent\n')
print_raw(' ~ \033[7m\\char\033[0m : print received bytes as character\n')
print_raw(' ~ \\dec : print received bytes as decimal number\n')
print_raw(' ~ \\dechex : print received bytes as decimal number and hexadecimal equivalent\n')
print_raw(' ~ \\dump : dump received bytes in dumpfile, if argument given use it as file name\n')
print_raw(' ~ \\exit : exits the script\n')
print_raw(' ~ \\getpath : prints working directory\n')
print_raw(' ~ \\help : prints this message\n')
print_raw(' ~ \033[7m\\hex\033[0m : print received bytes as hexadecimal number\n')
print_raw(' ~ \\keeplog : do not delete programme log\n')
print_raw(' ~ \\license : prints license information\n')
print_raw(' ~ \\list : prints connected devices\n')
print_raw(' ~ \\mute : do not print received received to terminal\n')
print_raw(' ~ \\nodump : stop dumping received bytes in dumpfile\n')
print_raw(' ~ \\pref : add bytes to send before transmitted data, arguments should be given as hexadecimal\n')
print_raw(' ~ \033[7m\\rand\033[0m : send random bytes, argument determines how many\n')
print_raw(' ~ \033[7m\\quit\033[0m : exits the script\n')
print_raw(' ~ \\safe : in non char mode, stop sending if non number given\n')
print_raw(' ~ \033[7m\\send\033[0m : send files\n')
print_raw(' ~ \\setpath : set directory for file operations, full or relative path, empty for cwd\n')
print_raw(' ~ \\suff : add bytes to send after transmitted data, arguments should be given as hexadecimal\n')
print_raw(' ~ \\unmute : print received received to terminal\n')
print_raw(' ~ \\unsafe : in non char mode, do not stop sending if non number given\n')
print_raw(' ~ \\@ : print the path to the connected device\n')
print_raw('\n Marked commands can be called with their first letter\n')
#listener daemon
def uart_listener(): #? if possible, keep the prompt already written in terminal when new received
print_raw(get_now())
print_info(' Listening...\n')
timer_stamp = 0
last_line = ''
last_timestamp = ''
byte_counter = 0
received_invalid = False
global listener_alive
global block_listener
while True: #main loop for listener
try:
read_byte = uart_conn.read()
if not listener_mute:
line_end = False
buff = ''
if char:
try:
buff = read_byte.decode()
line_end = (buff == '\n')
if line_end:
buff = ''
except UnicodeError:
buff = '\033[2m[\033[0m\033[95m' + hex(int.from_bytes(read_byte, byteorder='little'))
buff += '\033[0m\033[2m]\033[0m'
received_invalid = True
except Exception as decode_err:
print_error(str(decode_err)+'\n')
print_warn('Ignoring received byte\n')
else:
val = int.from_bytes(read_byte, byteorder='little')
if dec_ow:
buff = str(val)
elif bin_ow:
buff = bin(val)
else:
buff = hex(val)
if hex_add:
buff += (' (' + hex(val) + ')')
buff += ' '
byte_brake = ((not char or received_invalid) and (byte_counter == 15)) or (byte_counter == 63)
if (timer_stamp < get_cpu_time()) or line_end or byte_brake or block_listener:
received_invalid = False
block_listener = False
byte_counter = 0
last_line = ''
last_timestamp = '\033[F' + '\n' + get_now() + ' \033[36mGot:\033[0m '
else:
print_raw('\033[F\r')
byte_counter += 1
last_line += buff
line = last_timestamp
if char:
line += ('\033[2m\'\033[0m'+last_line+'\033[2m\'\033[0m')
else:
line += last_line
print_raw(line + '\n')
print_input_symbol()
sys.stdout.flush()
timer_stamp = get_cpu_time() + 100000
if dumpfile is not None:
try:
dump_path = working_directory + '/' + dumpfile
dump = open(dump_path, 'ab')
dump.write(read_byte)
dump.close()
except Exception as dump_error:
print_error('Cannot dump to file \033[0m' + dumpfile + '\033[31m!\n')
print_error(str(dump_error) + '\n')
except serial.SerialException:
print_fatal('\033[F\nConnection to ' + serial_path + ' lost!\n')
print_warn('Killing daemon...\n')
listener_alive = False
break
except Exception as listener_error:
print_fatal(str(listener_error) + '\n')
print_warn('Killing daemon...\n')
listener_alive = False
break
#Main function
if __name__ == '__main__':
start_time = datetime.now()
log_directory = '.uart_tool'
program_log = None
log_lock = False
print_info('Welcome to the UART tool v1.4.3!\n')
baud = 115200
serial_path = '/dev/ttyUSB'
data_size = serial.EIGHTBITS
stop_size = serial.STOPBITS_ONE
par = serial.PARITY_NONE
par_str = 'no'
search_range = 10
#check arguments for custom settings
try:
while len(sys.argv) > 1:
current = sys.argv.pop(-1)
current = current.strip()
if current.isnumeric() or current == '1.5' or current == '1,5':
if current == '1,5':
current = 1.5
else:
current = float(current)
if 20 > current > 10:
search_range = int(current)
elif current == 8:
data_size = serial.EIGHTBITS
elif current == 7:
data_size = serial.SEVENBITS
elif current == 6:
data_size = serial.SIXBITS
elif current == 5:
data_size = serial.FIVEBITS
elif current == 2:
stop_size = serial.STOPBITS_TWO
elif current == 1.5:
stop_size = serial.STOPBITS_ONE_POINT_FIVE
elif current == 1:
stop_size = serial.STOPBITS_ONE
elif current > 1999:
baud = int(current)
elif current.casefold() == 'even' or current.casefold() == 'e':
par = serial.PARITY_EVEN
par_str = 'even'
elif current.casefold() == 'odd' or current.casefold() == 'o':
par = serial.PARITY_ODD
par_str = 'odd'
elif current.casefold() == 'mark' or current.casefold() == 'm':
par = serial.PARITY_MARK
par_str = 'mark'
elif current.casefold() == 'space' or current.casefold() == 's':
par = serial.PARITY_SPACE
par_str = 'space'
elif current.casefold() == 'no' or current.casefold() == 'n':
continue
elif current.casefold().strip('--') == 'help' or current.casefold() == '-h':
print('\033[FUsage: uart.py [arg] ')
print_info(' Arguments can be the uart configurations or one of the following commands:\n\n')
print_info(' --interactive (-i): interactive start up, tool asks for uart configurations\n')
print_info(' --help (-h): Print this message\n')
print_info(' --search (-s): Search for connected devices\n')
print_info('\n Uart configurations can be given in any order\n')
sys.exit(0)
elif current.casefold() == '-i' or current.casefold().strip('--') == 'interactive':
print_info('\nInteractive configuration mode\nLeave empty for default values\n\n')
while True: #ask baud rate
cin = str(input('Baud rate: '))
cin = cin.strip()
if cin == '':
print_raw('\033[FBaud rate: ')
print_info(str(baud) + '\n')
break
if not cin.isnumeric():
print_warn('Baud rate must be an integer!\n')
continue
cin = int(cin)
if cin > 1199:
baud = cin
break
else:
print_warn('Minimum baud rate should be 1.2k\n')
while True: #ask data size
cin = str(input('Data size: '))
cin = cin.strip()
if cin == '':
print_raw('\033[FData size: ')
print_info(str(data_size) + '\n')
break
if not cin.isnumeric():
print_warn('Data size must be an integer!\n')
continue
cin = int(cin)
if 4 < cin < 9:
data_size = cin
break
else:
print_warn('Data size should be either 5, 6, 7 or 8\n')
while True: #ask parity
cin = str(input('Parity: '))
cin = cin.strip()
if cin == '':
print_raw('\033[FParity: ')
print_info(par + '\n')
break
if cin.casefold() == 'odd' or cin.casefold() == 'o':
par = serial.PARITY_ODD
par_str = 'odd'
break
elif cin.casefold() == 'even' or cin.casefold() == 'e':
par = serial.PARITY_EVEN
par_str = 'even'
break
elif cin.casefold() == 'mark' or cin.casefold() == 'm':
par = serial.PARITY_MARK
par_str = 'mark'
break
elif cin.casefold() == 'space' or cin.casefold() == 's':
par = serial.PARITY_SPACE
par_str = 'space'
break
elif cin.casefold() == 'none' or cin.casefold() == 'n' or cin.casefold() == 'no':
break
else:
print_warn('Parity should be odd, even, mark, space or none\n')
while True: #ask stop bit
cin = str(input('Stop bit size: '))
cin = cin.strip()
if cin == '':
print_raw('\033[FStop bit size: ')
print_info(str(stop_size) + '\n')
break
try:
cin = float(cin)
except ValueError:
print_warn('Stop bit size must be a float!\n')
continue
except Exception as config_error:
print_error(str(config_error)+'\n')
continue
if cin == 1 or cin == 2:
stop_size = cin
break
elif cin == 1.5:
stop_size = serial.STOPBITS_ONE_POINT_FIVE
break
else:
print_warn('Stop bit size should be either 1, 1.5 or 2\n')
if serial_path == '/dev/ttyUSB':
while True: #ask serial path
cin = str(input('Device: '))
cin = cin.strip()
if cin == '':
print_raw('\033[FDevice: ')
print_info('Search\n')
break
if not cin.startswith('tty'):
print_warn('Device name should start with tty\n')
continue
try:
try_path = '/dev/' + cin
uart = Serial(try_path, timeout=1)
uart.close()
serial_path = try_path
break
except serial.SerialException:
print_error('Cannot connect to device \033[0m' + cin + '\033[31m!\n')
except Exception as conn_error:
print_error(str(conn_error) + '\n')
elif current.casefold().strip('--') == 'search' or current.casefold() == '-s':
print_info('\nSearching for connected devices...\n')
found_dev = 0
non_res_dev = 0
poll_path = '/dev/ttyUSB'
for i in range(search_range + 1):
current = poll_path + str(i)
if os.path.exists(current):
try:
uart_conn = Serial(current, timeout=1)
uart_conn.close()
print_success('\nFound ttyUSB' + str(i))
found_dev += 1
except serial.SerialException:
print_warn('\nFound ttyUSB' + str(i) + ', but cannot connect!')
non_res_dev += 1
except Exception as search_err:
print_warn(str(search_err)+'\n')
print_info('Ignoring...\n')
poll_path = '/dev/ttyACM'
for i in range(search_range + 1):
current = poll_path + str(i)
if os.path.exists(current):
try:
uart_conn = Serial(current, timeout=1)
uart_conn.close()
print_success('\nFound ttyACM' + str(i))
found_dev += 1
except serial.SerialException:
print_warn('\nFound ttyACM' + str(i) + ', but cannot connect!')
non_res_dev += 1
except Exception as search_err:
print_warn(str(search_err)+'\n')
print_info('Ignoring...\n')
poll_path = '/dev/ttyCOM'
for i in range(search_range + 1):
current = poll_path + str(i)
if os.path.exists(current):
try:
uart_conn = Serial(current, timeout=1)
uart_conn.close()
print_success('\nFound ttyCOM' + str(i) + '\n')
found_dev += 1
except serial.SerialException:
print_warn('\nFound ttyCOM' + str(i) + ', but cannot connect!')
non_res_dev += 1
except Exception as search_err:
print_warn(str(search_err)+'\n')
print_info('Ignoring...\n')
print_raw('\n\n')
if found_dev != 0:
print_success('Found ')
print_raw(str(found_dev))
if found_dev == 1:
print_success(' device!\n')
else:
print_success(' devices!\n')
if non_res_dev != 0:
print_warn('Found ')
print_raw(str(non_res_dev))
if non_res_dev == 1:
print_success(' device, but cannot connect to it!\n!\n')
else:
print_success(' devices, but cannot connect to them!\n!\n')
if non_res_dev == 0 and found_dev == 0:
print_error('Cannot find any devices!\n')
sys.exit(0)
elif current.startswith('tty'):
serial_path = '/dev/' + current
try:
uart_conn = Serial(serial_path, baud, timeout=1)
uart_conn.close()
except serial.SerialException:
print_fatal('\nCannot open ' + serial_path)
print_info('\nExiting...\n')
sys.exit(1)
except Exception as dev_err:
print_fatal(str(dev_err) + '\n')
print_info('\nExiting...\n')
sys.exit(1)
else:
print_warn('\nInvalid argument:' + current)
print_info('\nSkipping...\n')
if serial_path == '/dev/ttyUSB': #if no device is given, poll for it
for i in range(search_range + 1):
current = serial_path + str(i)
try:
uart_conn = Serial(current, baud, timeout=1)
uart_conn.close()
serial_path = current
except serial.SerialException:
continue
except Exception as dev_err:
print_fatal(str(dev_err) + '\n')
print_info('\nExiting...\n')
sys.exit(1)
if serial_path == '/dev/ttyUSB':
serial_path = '/dev/ttyACM'
for i in range(search_range + 1):
current = serial_path + str(i)
try:
uart_conn = Serial(current, baud, timeout=1)
uart_conn.close()
serial_path = current
except serial.SerialException:
continue
except Exception as dev_err:
print_fatal(str(dev_err) + '\n')
print_info('\nExiting...\n')
sys.exit(1)
if serial_path == '/dev/ttyACM':
serial_path = '/dev/ttyCOM'
current = ''
for i in range(search_range + 1):
current = serial_path + str(i)
try:
uart_conn = Serial(current, baud, timeout=1)
uart_conn.close()
serial_path = current
except serial.SerialException:
continue
except Exception as dev_err:
print_fatal(str(dev_err) + '\n')
print_info('\nExiting...\n')
sys.exit(1)
if serial_path == '/dev/ttyCOM':
print_fatal('\nCannot find any devices, exiting...\n')
sys.exit(1)
except KeyboardInterrupt:
print_warn('\nInterrupted by user\n')
print_info('\nExiting...\n')
sys.exit(1)
except Exception as arg_err:
print_fatal('\n' + str(arg_err) + '\n')
print_info('\nExiting...\n')
sys.exit(1)
#Software Configurations
global block_listener
char = False
dec_ow = False
bin_ow = False
hex_add = False
safe_tx = False
prefix = None
suffix = None
keep_log = False
listener_mute = False
working_directory = os.getcwd()
dumpfile = None
log_listener_check = True
log_lock = False
#Prepare program log
try:
if not os.path.isdir(log_directory):
os.mkdir(log_directory)
program_log = log_directory + '/uart_' + start_time.strftime('%Y-%m-%d_%Hh%Mm%Ss') + '.log'
log = open(program_log, 'a')
log.write(get_log_time(start_time))
log.write('debug: program start\n')
log.write(get_log_time(datetime.now()))
log.write('debug: log start\n')
log.close()
except Exception as e:
program_log = None
print_error(str(e)+'\n')
print_info('Running without a log\n')
try:
uart_conn = Serial(serial_path, baud, data_size, par, stop_size)
except Exception as e:
print_fatal(str(e) + '\n')
sys.exit(2)
print_success('\nConnected to ' + serial_path)
print_info('\nConfigurations: ' + str(baud) + ' ' + str(data_size) + ' bits with ' + par_str + ' parity and ' + str(
stop_size) + ' stop bit(s)\n\n')
#Set up listener daemon
try:
listener_daemon = threading.Thread(target=uart_listener, daemon=True)
listener_daemon.start()
except Exception as e:
print_fatal(str(e) + '\n')
sys.exit(4)
listener_alive = True
block_listener = False
cin = ''
print_input_symbol()
while True: #main loop for send
try:
signal.signal(signal.SIGALRM, check_listener)
signal.alarm(1)
cin = input() #Wait for input
stamp = '\033[F' + get_now() + ' '
signal.signal(signal.SIGALRM, process_timeout)
signal.alarm(1800) #Half an hour
cin = cin.strip()
if cin == '':
print_time_stamp() #print timestamp
print_info('Nothing to do!\n', False)
print_input_symbol()
continue
#command handling
if cin == '\\quit' or cin == '\\exit' or cin == '\\q':
print_time_stamp() #print timestamp
break
elif cin == '\\help':
print_time_stamp() #print timestamp
print_info('Help\n', False)
print_help()
block_listener = True
print_input_symbol()
continue
elif cin == '\\license':
print_time_stamp() #print timestamp
print_info('License\n', False)
print_raw('EUPL-1.2\n')
print_raw('Full text: https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12\n')
block_listener = True
print_input_symbol()
continue
elif cin == '\\char' or cin == '\\c':
char = True
dec_ow = False
bin_ow = False
hex_add = False
print_time_stamp() #print timestamp
print_info('Received bytes will be printed as character\n')
block_listener = True
print_input_symbol()
continue
elif cin == '\\hex' or cin == '\\h':
print_time_stamp() #print timestamp
print_info('Received bytes will be printed as hexadecimal number\n')
block_listener = True
char = False
dec_ow = False
bin_ow = False
hex_add = False
print_input_symbol()
continue
elif cin == '\\dec':
print_time_stamp() #print timestamp
print_info('Received bytes will be printed as decimal number\n')
block_listener = True
char = False
dec_ow = True
bin_ow = False
hex_add = False
print_input_symbol()
continue
elif cin == '\\bin':
print_time_stamp() #print timestamp
print_info('Received bytes will be printed as binary number\n')
block_listener = True
char = False
dec_ow = False
bin_ow = True
hex_add = False
print_input_symbol()
continue
elif cin == '\\dechex':
print_time_stamp() #print timestamp
print_info('Received bytes will be printed as decimal number and hexadecimal equivalent\n')
block_listener = True
char = False
dec_ow = True
bin_ow = False
hex_add = True
print_input_symbol()
continue
elif cin == '\\binhex':
print_time_stamp() #print timestamp
print_info('Received bytes will be printed as binary number and hexadecimal equivalent\n')
block_listener = True
char = False
dec_ow = False
bin_ow = True
hex_add = True
print_input_symbol()
continue
elif cin == '\\@':
print_time_stamp() #print timestamp
print_info('Connected to: \033[0m' + serial_path + '\n')
print_input_symbol()
continue
elif cin == '\\keeplog':
print_time_stamp() #print timestamp
if program_log is not None:
keep_log = True
print_info('Programme log will be kept\n')
else:
try:
log_lock = True
program_log = log_directory + '/uart_' + start_time.strftime('%Y%m%dh%Hm%Ms%S') + '.log'
log = open(program_log, 'a')
log.write(get_log_time(start_time))
log.write('program start\n')
log.write(get_log_time(datetime.now()))
log.write('log start, tool run without a log!\n')
log.close()
print_info('New log generated\n')
keep_log = True
except Exception as e:
print_error('Cannot keep log\n')
print_error(str(e)+'\n')
finally:
log_lock = False
print_input_symbol()
continue
elif cin == '\\safe':
print_time_stamp() #print timestamp
print_info('Safe transmit mode enabled\n')
block_listener = True
safe_tx = True
print_input_symbol()
continue
elif cin == '\\unsafe':
print_time_stamp() #print timestamp
print_info('Safe transmit mode disabled\n')
block_listener = True
safe_tx = False
print_input_symbol()
continue
elif cin == '\\unmute':
print_time_stamp() #print timestamp
print_info('Listener unmuted\n')
listener_mute = False
print_input_symbol()
continue
elif cin == '\\mute':
print_time_stamp() #print timestamp
print_info('Listener muted\n')
listener_mute = True
if dumpfile is None:
print_warn('Dumping is disabled, received data will be discarded!\n')
print_input_symbol()
continue
elif cin == '\\nodump':
print_time_stamp() #print timestamp
print_info('Dumping disabled\n')
dumpfile = None
if listener_mute:
print_warn('Listener is muted, received data will be discarded!\n')
block_listener = True
print_input_symbol()
continue
elif cin.startswith('\\dump'):
cin = cin[5:]
tmp_file = None
cin = cin.split(' ')
print_time_stamp() #print timestamp
if len(cin) == cin.count(''):
tmp_file = 'uart_received.bin'
else:
for arg in cin:
if arg != '':
if tmp_file is None:
tmp_file = arg
else:
print_warn('Ignoring extra arguments\n', False)
break
if not os.path.isfile(working_directory + '/' + tmp_file):
try:
tmp_dump = open(working_directory + '/' + tmp_file, 'x')
tmp_dump.close()
except Exception as e:
print_error('Cannot find or create file \033[0m' + tmp_file + '\033[31m in current path!\n')
print_error(str(e) + '\n')
print_input_symbol()
continue
try:
tmp_dump = open(working_directory + '/' + tmp_file, 'r')
tmp_dump.close()
dumpfile = tmp_file
print_info('Received bytes will be dumped to \033[0m' + dumpfile + '\n')
except Exception as open_error:
print_error('Cannot open file \033[0m' + tmp_file + '\033[31m!\n')
print_error(str(open_error)+'\n')
block_listener = True
print_input_symbol()
continue
elif cin.startswith('\\send') or cin.startswith('\\s ') or cin == '\\s':
sendByte = 0
sendFile = 0
if cin.strip() == '\\send' or cin.strip() == '\\s':
block_listener = True
files = input('Please provide the name of the file(s): ')
else:
if cin.strip() == '\\send':
cin = cin[5:]
else:
cin = cin[2:]
files = cin.strip()
files = files.split(' ')
for filename in files:
if filename != '':
file = None
try:
full_path = working_directory + '/' + filename
file = open(full_path, 'rb')
sendFile += 1
except Exception as open_err:
print_time_stamp() #print timestamp
print_error('Cannot open file \033[0m' + filename + '\033[31m!\n')
print_error(str(open_err) + '\n')
if safe_tx:
print_info('Breaking\n')
break
else:
print_info('Continuing\n')
continue
byte = file.read(1)
while byte != b'':
serial_write(byte)
sendByte += 1
byte = file.read(1)
file.close()
print_time_stamp() #print timestamp
if sendFile == 0:
print_warn("Didn't write anything\n")
else:
print_info('Wrote ' + str(sendByte) + ' bytes from ' + str(sendFile) + ' file(s)\n')
block_listener = True
print_input_symbol()
continue
elif cin.startswith('\\rand') or cin.startswith('\\r ') or cin == '\\r':
random_byte_count = 1
print_time_stamp() #print timestamp
if cin.strip() != '\\rand' and cin.strip() != '\\r':
if cin.startswith('\\rand'):
cin = cin[5:].strip()
else:
cin = cin[2:].strip()
arg = cin.split(' ')
try:
temp = int(arg[0])
except ValueError:
print_error('Argument should be a number!\n', False)
print_input_symbol()
continue
except Exception as rand_err:
print_error(str(rand_err)+'\n')
print_input_symbol()
continue
if len(arg) != 1:
print_warn('Ignoring extra arguments\n', False)
random_byte_count = temp
print_info('\033[2mSending \033[0m'+str(random_byte_count)+'\033[2m random byte(s)\n')
block_listener = True
random.seed()
if random_byte_count > 100:
print_info(('\n\033[F\033[0m' + get_now() + '\033[2m Too many bytes to show!\n'), False)
block_listener = True
for i in range(random_byte_count):
random_byte = random.randint(0, 255)
serial_write(random_byte.to_bytes(1, byteorder='little'))
else:
random_bytes = ''
for i in range(random_byte_count):
random_byte = random.randint(0, 255)
serial_write(random_byte.to_bytes(1, byteorder='little'))
random_bytes += (hex(random_byte)+' ')
print_raw('\n\033[F' + get_now() + ' \033[33mSend: \033[0m\033[96m'+random_bytes+'\033[0m\n')
block_listener = True
block_listener = True
print_input_symbol()
continue
elif cin == '\\list':
print_time_stamp() #print timestamp
print_info('Current connection: \033[0m\033[32m' + serial_path + '\n', False)
print_info('Other devices:\n', False)
poll_list = ['/dev/ttyUSB', '/dev/ttyACM', '/dev/ttyCOM']
for poll_path in poll_list:
for i in range(search_range + 1):
current = poll_path + str(i)
if current == serial_path:
continue
if os.path.exists(current):
print_info('~ ', False)
try:
uart_conn = Serial(current, timeout=1)
uart_conn.close()
print_raw(current + '\n')
except serial.SerialException:
print_warn(current + ', cannot connect!\n', False)
except Exception as search_err:
print_error(current + ', ' + str(search_err) + '\n', False)
block_listener = True
print_input_symbol()
continue
elif cin == '\\getpath':
print_time_stamp() #print timestamp
print_info('Current path: \033[0m' + working_directory + '\n')
block_listener = True
print_input_symbol()
continue
elif cin.startswith('\\setpath'):
cin = cin.strip()
if cin == '\\setpath':
working_directory = os.getcwd()
else:
cin = cin[8:]
cin = cin.split(' ')
tmpdir = None
print_time_stamp() #print timestamp
for arg in cin:
if arg != '':
if tmpdir is None:
tmpdir = arg
else:
print_warn('Ignoring extra arguments\n', False)
break
if tmpdir.startswith('~/'):
tmpdir = str(os.path.expanduser("~")) + tmpdir[1:]
elif not tmpdir.startswith('/'):
tmpdir = os.getcwd() + '/' + tmpdir
if os.path.isdir(tmpdir):
working_directory = tmpdir
else:
print_raw(tmpdir)
print_error(' is not a valid directory path!\n')
print_input_symbol()
continue
print_info('Working directory set to \033[0m' + working_directory + '\n')
block_listener = True
print_input_symbol()
continue
elif cin.startswith('\\pref'):
cin = cin[5:]
try: