-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnicFWutil.py
1148 lines (857 loc) · 33.3 KB
/
nicFWutil.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
import serial
import sys
import argparse
from time import sleep
import struct
import re
DEFAULT_DEVICE = "/dev/ttyUSB0"
DEFAULT_SERIAL_TIMEOUT = 1
DEFAULT_KEY_PUSH_TIME = 0.33 # time to sleep after each key send/release action
# nicFW commands
CMD_START_REMOTE_SESSION = b'\x4A' # w/ Ack
CMD_END_REMOTE_SESSION = b'\x4B' # w/ Ack
CMD_READ_EEPROM = b'\x30' # w/ Ack
CMD_WRITE_EEPROM = b'\x31' # w/ Ack
CMD_READ_BATTERY_ADC = b'\x32' # w/ Ack
CMD_DISABLE_RADIO = b'\x45' # w/ Ack
CMD_ENABLE_RADIO = b'\x46' # w/ Ack
CMD_FLASHLIGHT_ON = b'\x47' # w/o Ack
CMD_FLASHLIGHT_OFF = b'\x48' # w/o Ack
CMD_RESET_RADIO = b'\x49' # w/o Ack
# dict for storing single channel data
channel = {
"number": 0,
"name" : "",
"rx_f": 0,
"tx_f": 0,
"rx_subtone" : 0,
"tx_subtone" : 0,
"tx_power" : 0,
"groups_str" : "0000",
"modulation" : "",
"bandwidth" : "",
"is_empty" : True
}
bandplan_mod = [ 'Ignore', 'FM', 'AM', 'USB', 'Enforce_FM', 'Enforce_AM', 'Enforce_USB', 'Enforce_None' ]
bandplan_bw = [ 'Ignore', 'Wide', 'Narrow', 'Enforce_Wide', 'Enforce_Narrow' ]
NoYes = [ 'No', 'Yes' ]
fm_band = [ 'West', 'Japan', 'World', 'Low_VHF' ]
sp_mod = ['FM', 'AM', 'USB' ]
# args
parser = argparse.ArgumentParser()
parser.add_argument("-d", "--device", help="serial device to communicate with radio (default /dev/ttyUSB0)")
parser.add_argument("-c", "--channel", type=int, help="channel number to edit/update/remove")
parser.add_argument("-n", "--name", help="channel name")
parser.add_argument("-tx", "--tx", type=int, help="TX frequency")
parser.add_argument("-rx", "--rx", type=int, help="RX frequency")
parser.add_argument("-txc", "--tx-ctcss", type=int, help="TX CTCSS tone")
parser.add_argument("-rxc", "--rx-ctcss", type=int, help="RX CTCSS tone")
parser.add_argument("-p", "--power", type=int, help="TX power")
parser.add_argument("-m", "--modulation", help="modulation")
parser.add_argument("-b", "--bandwidth", help="bandwidth")
parser.add_argument("-g", "--groups", help="groups to add channel to (eg. ABCD, A00F)")
parser.add_argument("-r", "--reset", action='store_true', help="reset radio")
parser.add_argument("--remove", action='store_true', help="remove channel")
parser.add_argument("-u", "--update", action='store_true', help="update existing channel")
parser.add_argument("-w", "--write", action='store_true', help="create new channel/overwrite existing one")
parser.add_argument("-f1", "--flashlight-on", action='store_true', help="turn flashlight ON")
parser.add_argument("-f0", "--flashlight-off", action='store_true', help="turn flashlight OFF")
parser.add_argument("-k", "--key", help="send KEY(s) sequence to radio")
parser.add_argument("-e", "--export-csv", help="export channels to CSV file")
parser.add_argument("-f", "--fixed-width", action='store_true', help="use fixed width data when exporting CSV")
parser.add_argument("-i", "--import-csv", help="import channels from CSV file")
parser.add_argument("-se", "--show-eeprom", action='store_true', help="read and print eeprom content")
parser.add_argument("-sb", "--show-bandplan", action='store_true', help="read and show Band Plan")
parser.add_argument("-ib", "--import-bandplan", help="import bandplan from file")
parser.add_argument("-sf", "--show-fmtuner", action='store_true', help="read and show FM Tunner channels")
parser.add_argument("-ssp", "--show-scan-presets", action='store_true', help="read and show Scan Presets")
parser.add_argument("--debug", action='store_true', help="enable debug messages")
args = parser.parse_args()
debug = args.debug
# check for no args
if not any(vars(args).values()):
parser.print_help()
sys.exit(2)
# count specified channel actions
action_count = 0
for i in (args.write, args.update, args.remove):
if i == True:
action_count += 1
# count specified modifiers
modifiers_count = 0
for i in (args.name, args.power, args.tx_ctcss, args.rx_ctcss, args.rx, args.tx, args.modulation, args.bandwidth, args.groups):
if i != None:
modifiers_count += 1
# check for multiple channel actions at once
if action_count > 1:
print("[ERR] choose only one action from [write/update/remove].")
sys.exit(2)
# check if modifiers is used with remove channel action
if args.remove != False and modifiers_count > 0:
print("[ERR] channel modifiers can't be used with channel remove action.")
sys.exit(2)
# check if at least one modifier is used with update channel action
if args.update != False and modifiers_count == 0:
print("[ERR] Update channel action need at least one channel modifier.")
sys.exit(2)
# check for modifiers used without proper channel action
if modifiers_count > 0 and args.update == False and args.write == False:
print("[ERR] channel modifiers used without channel action.")
sys.exit(2)
# check for channel modifiers used with import/export action
if modifiers_count > 0 and (args.export_csv != None or args.import_csv != None):
print("[ERR] channel modifiers used without import/export action.")
sys.exit(2)
# check for using fixed width data without export action
if args.fixed_width != False and args.export_csv == None:
print("[ERR] fixed width data modifier used without export action.")
sys.exit(2)
# check for using import and export action at once
if args.import_csv != None and args.export_csv != None:
print("[ERR] import and export action used at once.")
sys.exit(2)
# require channel number for channel actions
if args.channel == None:
if args.write != False or args.update != False or args.remove != False:
print("[ERR] channel number has been not specified.");
exit (2)
# if device is not specified, use default one
device = args.device
if device is None:
device = DEFAULT_DEVICE
if debug:
print("[DBG] Using '{}' device...".format(device))
# Try to open serial device
try:
port = serial.Serial(device, baudrate=38400, timeout=DEFAULT_SERIAL_TIMEOUT)
except serial.serialutil.SerialException:
print("[ERR] problem occured when trying to open '{}' device".format(device))
sys.exit(2)
def write_cmd(cmd, check_ack=False):
port.write(cmd)
if check_ack == True:
ack = port.read(1)
if ack != cmd:
print("[ERR] Unable to communicate with nicFW -- there was no valid ACK for {} command ({} recaived).".format(cmd,ack))
sys.exit(2)
def disable_radio():
write_cmd(CMD_DISABLE_RADIO, check_ack=True)
def enable_radio():
write_cmd(CMD_ENABLE_RADIO, check_ack=True)
def reset_radio():
write_cmd(CMD_RESET_RADIO)
def enable_remote():
write_cmd(CMD_START_REMOTE_SESSION)
def disable_remote():
write_cmd(CMD_END_REMOTE_SESSION)
# calculate checksum of bytearray
def calc_checksum(bytes):
checksum = 0
for b in bytes:
checksum += b
return (checksum % 256).to_bytes(1);
exit_info = None
def exit(err_code):
if exit_info != None:
print(exit_info)
sys.exit(err_code)
# convert variable to int
# - if variable is str check if contains only digits
def conv2int(desc, var):
if isinstance(var, str):
if var.isnumeric() == False:
print("[ERR] {} must contain only digits, but additional characters in '{}' has been found.".format(desc,var))
exit(2)
return int(var)
else:
return var
# check if channel numer is in range
def check_channel_number(channel_number):
number = conv2int ("Channel number", channel_number)
if number < 1 or number > 198:
print("[ERR] wrong channel number '{}' -- should be in the range from 1 to 198.".format(channel_number))
exit(2)
return number
# validate group names
def check_groups(groups_str):
groupsUP = ""
for group in groups_str:
group = group.upper()
groupsUP += group
if (ord(group) < 65 or ord(group)>79) and group != '0': # 0 for allowing eg. 000A to assing only 4th group
print("[ERR] group should be letter betwen A-O (or 0 for group) but '{}' has been found".format(group))
sys.exit(1)
if len(groups_str)>4:
print ("[ERR] you can assign up to 4 groups only.")
exit(2)
return groupsUP
# validade channel name
# TODO any forbidden characters in name?
def check_name(name):
name_len = len(name)
if name_len > 12:
print("[WARN] name has been trimmed to 12 characters.")
name = name[:12]
# fill name to 12 bytes
if name_len < 12:
for i in range(12-name_len):
name += '\0' # fill up with \0s
return name
# validate frequency
def check_frequency(frequency,zero_allowed=False):
number = conv2int ("Frequency", frequency)
if number == 0 and zero_allowed == True:
return 0
if number < 1800000 or number > 130000000:
print("[ERR] Frequency should be in the range from 1800000 to 130000000.")
exit(2)
return number
# check subtone
# TODO add supporot for DCS
def check_subtone(subtone):
number = conv2int ("Subtone", subtone)
if (number < 670 or number > 2541) and number != 0:
print("[ERR] Subtone should be in the range from 670 to 2541 range (or 0 to disable).")
exit(2)
return number
def check_power(power):
number = conv2int ("Power", power)
if number < 0 or number > 255:
print("[ERR] Power should be in the range from 0 to 255.")
exit(2)
return number
def check_bandwidth(bandwidth):
if bandwidth.upper() in [ 'WIDE', 'NARROW' ]:
return bandwidth
else:
print("[ERR] Bandwidth should be in [ 'Wide', 'Narrow' ], but '{}' found".format(bandwidth))
exit(2)
return bandwidth
def check_modulation(modulation):
if modulation.upper() in [ 'AUTO', 'FM', 'AM', 'USB' ]:
return modulation
else:
print("[ERR] Modulation should be in [ 'Auto', 'FM', 'AM', 'USB' ], but '{}' found".format(modulation))
exit(2)
return modulation
# convert group letter (A-O) to number (1-15)
def group_a2i(group):
if ord(group) < 65 or ord(group)>79:
return 0
else:
return ord(group.upper())-64
# convert group string to group bytes[2]
def group_s2b(groups_str):
for i in range(0,4-len(groups_str)):
groups_str += '@' # fill up undefined groups
groups_arr = bytearray(2)
groups_arr[0] |= group_a2i(groups_str[0])
groups_arr[0] |= group_a2i(groups_str[1]) << 4
groups_arr[1] |= group_a2i(groups_str[2])
groups_arr[1] |= group_a2i(groups_str[3]) << 4
return groups_arr
# convert array[4] of group numbers to array[4]/string of letters
def group_an2s(group_arr):
str = ""
for group in group_arr:
if group > 0 and group<=15:
str += chr(group+64)
else:
str += '0'
return str
# convert group bytes[2] to array[4] of group numbers
def group_b2an(group_bytes):
group_array = bytearray(4)
group_array[0] = group_bytes[0] & 0b00001111;
group_array[1] = group_bytes[0] >> 4;
group_array[2] = group_bytes[1] & 0b00001111;
group_array[3] = group_bytes[1] >> 4;
return group_array
# DEBUG groups
#ga = group_s2b("A0C@")
#gs = group_an2s(group_b2an(ga))
#print("{} : {}".format(ga,gs))
#sys.exit(1)
# print channel data
def print_channel():
print ("{:10s} : CH-{:03d}".format("channel", channel['number']))
print ("{:10s} : {}".format("name", channel['name']))
print ("{:10s} : {}".format("RX freq", channel['rx_f']))
print ("{:10s} : {}".format("TX freq", channel['tx_f']))
print ("{:10s} : {}".format("RX subtone", channel['rx_subtone']))
print ("{:10s} : {}".format("TX subtone", channel['tx_subtone']))
print ("{:10s} : {}".format("TX power", channel['tx_power']))
print ("{:10s} : {}".format("group", channel['groups_str'])) # group_an2s(group_array')
print ("{:10s} : {}".format("bandwidth", channel['bandwidth']))
print ("{:10s} : {}".format("modulation", channel['modulation']))
# decode channel data received from radio
def decode_channel_data(data):
global channel
group_array = bytearray(4)
channel['rx_f'] = int.from_bytes(data[0:4], 'little')
channel['tx_f'] = int.from_bytes(data[4:8], 'little')
channel['rx_subtone'] = int.from_bytes(data[8:10], 'little')
channel['tx_subtone'] = int.from_bytes(data[10:12], 'little')
channel['tx_power'] = data[12]
# group_bytes = int.from_bytes(data[13:14], 'little')
# mod_bw = int.from_bytes(data[15:16], 'little')
# reserved = int.from_bytes(data[16:20], 'little')
channel['name'] = data[20:32].decode('utf-8', 'replace')
channel['groups_str'] = group_an2s(group_b2an([data[13],data[14]]))
if data[15] & 0b00000001:
bandwidth = "Narrow"
else:
bandwidth = "Wide"
channel['bandwidth'] = bandwidth
match (data[15] >> 1) & 0b00000011:
case 0:
modulation = "Auto"
case 1:
modulation = "FM"
case 2:
modulation = "AM"
case 3:
modulation = "USB"
channel['modulation'] = modulation
def encode_channel_data():
global channel
mod_bw = bytearray(2)
reserved = [ 255, 255, 255, 255]
mod = 0
match channel['modulation'].upper():
case "AUTO":
mod = 0
case "FM":
mod = 1
case "AM":
mod = 2
case "USB":
mod = 3
case _:
print("[ERR] Wrong modulation value ({}).".format(channel['modulation']))
sys.exit(2)
bw = 0
match channel['bandwidth'].upper():
case "WIDE":
bw = 0
case "NARROW":
bw = 1
case _:
print("[ERR] Wrong bandwidth value ({}).".format(bw))
sys.exit(2)
mod_bw = (mod<<1) | bw
mod_bw |= 0b11111000 # add reserved bits as 1
data = bytearray()
data.extend(channel['rx_f'].to_bytes(4, byteorder='little'))
data.extend(channel['tx_f'].to_bytes(4, byteorder='little'))
data.extend(channel['rx_subtone'].to_bytes(2, byteorder='little'))
data.extend(channel['tx_subtone'].to_bytes(2, byteorder='little'))
data.append(channel['tx_power'])
data.extend(group_s2b(channel['groups_str']))
data.append(mod_bw)
data.extend(reserved)
data.extend(channel['name'].encode())
data_len = len(data)
if data_len != 32:
print("[ERR] encoded data has wrong size ({} but should be {} bytes), something went terribly wrong.".format(data_len,32))
sys.exit(2)
return data
# get eeprom block (32 bytes)
def get_eeprom_block(address):
port.write(CMD_READ_EEPROM)
port.write([address])
ack = port.read(1)
# if ack != CMD_READ_EEPROM:
# print("[ERR] no Ack.")
# sys.exit(2)
data = port.read(32)
checksum_r = port.read(1)
if checksum_r != calc_checksum(data):
print ("[ERR] received data checksum mismatch!")
sys.exit(2)
if debug:
print ("[DBG] received checksum OK")
return data
# read channel bytes from radio
def get_channel(channel_number):
global channel
disable_radio()
data = get_eeprom_block(channel_number+1)
enable_radio()
if data == b'':
print("[ERR] received empy channel data!")
sys.exit(2)
# check if channel has only 0xff values (is empty)
is_empty = True
for i in data:
if ( i != 255):
is_empty = False
break
channel['is_empty'] = is_empty
channel['number'] = channel_number
# decode channel bytes to channel variables
if is_empty == False:
decode_channel_data(data)
# write channel bytes to radio
def write_channel_bytes(channel_number,data_bytes):
global channel
checksum = calc_checksum(data_bytes)
if debug:
print("[DBG] bytes to write:{} checksum:{}".format(data_bytes,checksum))
disable_radio()
port.write(CMD_WRITE_EEPROM)
port.write([channel_number+1])
port.write(data_bytes)
port.write(checksum)
ack = port.read(1)
enable_radio()
if ack == CMD_WRITE_EEPROM:
if debug:
print("[DBG] write OK")
else:
print("[ERR] invalid ACK after write, something went wrong!")
sys.exit(2)
# prepare channel data for write
def write_channel():
global channel
if args.name is not None:
channel['name'] = check_name(args.name)
else:
channel['name'] = check_name(channel['name'])
if args.rx is not None:
channel['rx_f'] = check_frequency(args.rx)
if args.tx is not None:
channel['tx_f'] = check_frequency(args.tx)
if args.tx_ctcss is not None:
channel['tx_subtone'] = check_subtone(args.tx_ctcss)
if args.rx_ctcss is not None:
channel['rx_subtone'] = check_subtone(args.rx_ctcss)
if args.power is not None:
channel['tx_power'] = check_power(args.power)
if args.groups is not None:
channel['groups_str'] = check_groups(args.groups)
if args.modulation is not None:
channel['modulation'] = check_modulation(args.modulation)
if args.bandwidth is not None:
channel['bandwidth'] = check_bandwidth(args.bandwidth)
print_channel()
data_w = encode_channel_data()
write_channel_bytes(channel['number'], data_w)
# optional radio reset after channel write (only if -r)
if args.reset:
disable_remote()
reset_radio()
sys.exit(0)
# writes previously generated (file import) ChannelsDict to radio
def write_channels_from_dict(ChannelsDict):
global channel
# for each channel number in radio...
for channel_number in range(1,199):
# show writing progress
if (channel_number)%11 == 0:
print("importing CH-{:03d}...CH-{:03d} ({:3.0f})%.".format(channel_number-10,channel_number,channel_number/198*100))
# check if channel is in dictionary
if channel_number in ChannelsDict.keys():
c = ChannelsDict[channel_number]
channel['name'] = c[0]
channel['rx_f'] = c[1]
channel['tx_f'] = c[2]
channel['rx_subtone'] = c[3]
channel['tx_subtone'] = c[4]
channel['tx_power'] = c[5]
channel['groups_str'] = c[6]
channel['bandwidth'] = c[7]
channel['modulation'] = c[8]
data_w = encode_channel_data()
# if not -- overwrite channel with 0xff
else:
data_w = bytearray([255]*32) # fill up with 0xff
if debug:
print("data_w: {}",format(data_w))
write_channel_bytes(channel_number,data_w)
print ("done.")
reset_radio()
sys.exit(0)
######################################################################################
######################################################################################
# MAIN
######################################################################################
######################################################################################
# check channel number
if args.channel != None:
channel['number'] = check_channel_number(args.channel)
# write/overwrite channel
if args.write:
# default values for the newly created channel
channel['rx_f'] = 14495000
channel['tx_f'] = 14495000
channel['rx_subtone'] = 0
channel['tx_subtone'] = 0
channel['tx_power'] = 0
channel['groups_str'] = "0000"
channel['modulation'] = "Auto"
channel['bandwidth'] = "Narrow"
channel['name']= "CH-{:03n}".format(channel['number'])
write_channel()
sys.exit()
# remove channel
if args.remove:
print("Removing channel CH-{:03d}".format(channel['number']))
data_w = bytearray([255]*32) # fill up with 0xff
write_channel_bytes(channel['number'], data_w)
print("Done.")
sys.exit(0)
# update channel
if args.update:
get_channel(channel['number'])
if channel['is_empty'] == False:
write_channel()
else:
print("Channel {} is empty -- cannot perform an UPDATE action!".format(channel['number']))
sys.exit()
# print info about channel
if args.channel:
get_channel(channel['number'])
if channel['is_empty'] == False:
print_channel()
else:
print("Channel {} is empty.".format(channel['number']))
sys.exit(0);
# turn flashlight on
if args.flashlight_on:
write_cmd(CMD_FLASHLIGHT_ON)
sys.exit(0)
# turn flashlight off
if args.flashlight_off:
write_cmd(CMD_FLASHLIGHT_OFF)
sys.exit(0)
# reset radio
if args.reset:
disable_remote()
reset_radio()
sys.exit(0)
# export all channels from radio to CSV file
if args.export_csv != None:
header = ""
file = args.export_csv
if args.fixed_width == False:
line_format = "{:d},{:s},{:d},{:d},{:d},{:d},{:d},{:s},{:s},{:s}\n"
header += "Channel number,Rx frequency,Tx frequency,Rx subtone,Tx subtone,Tx power,Groups,Bandwidth,Modulation\n"
else:
line_format = "{:03d},{:12s},{:9d},{:9d},{:5d},{:5d},{:3d},{:4s},{:6s},{:4s}\n"
header += "CH#,Name , Rx freq, Tx freq,RxSub,TxSub,PWR,Grp ,Bwidth,Modulation\n"
try:
f = open(file,"w")
except OSError:
print("[ERR] Could not open/write file '{}'".format(file))
sys.exit(2)
# write file header
if header != "":
f.write(header)
for channel_number in range(1,199):
get_channel(channel_number)
# show writing progress
if (channel_number)%11 == 0:
print("exporting CH-{:03d}...CH-{:03d} ({:3.0f})%.".format(channel_number-10,channel_number,channel_number/198*100))
# write to file only valid channels
if channel['is_empty'] == False:
f.write(line_format.format(
channel_number,
channel['name'].rstrip('\0'),
channel['rx_f'],
channel['tx_f'],
channel['rx_subtone'],
channel['tx_subtone'],
channel['tx_power'],
channel['groups_str'],
channel['bandwidth'],
channel['modulation'])
)
f.close
print ("done.")
sys.exit(0);
# import channels from CSV file
if args.import_csv != None:
# dictionary where channels data readed from file will be stored
ChannelsDict = {}
try:
file = open(args.import_csv, "r")
except OSError:
print("[ERR] Could not open/read file '{}'".format(args.import_csv))
sys.exit(2)
channels = {}
lcount = 0
for line in file:
line = line.rstrip('\n')
lcount += 1
# skip first line (header)
if lcount == 1:
continue
# split line csv data by ','
csv_data = line.split(",")
# check array size
if len(csv_data) != 10:
print("[ERR] line {} has incorrect number of fields".format(lcount))
sys.exit(2)
# set additional info on check fail
exit_info = "[ERR] import failed on line {}".format(lcount)
# check and import channel settings
channel_number = check_channel_number(csv_data[0].strip(' '))
name = check_name(csv_data[1].rstrip(' '))
rx_f = check_frequency(csv_data[2].strip(' '))
tx_f = check_frequency(csv_data[3].strip(' '))
rx_subtone = check_subtone(csv_data[4].strip(' '))
tx_subtone = check_subtone(csv_data[5].strip(' '))
tx_power = check_power(csv_data[6].strip(' '))
groups = check_groups(csv_data[7])
bandwidth = check_bandwidth(csv_data[8].strip(' '))
modulation = check_modulation(csv_data[9].strip(' '))
if debug:
print ("[DBG] file read: {} {} {} {} {} {} {} {} {} {}".format(channel_number,name,rx_f,tx_f,rx_subtone,tx_subtone,tx_power,groups,bandwidth,modulation))
# check for duplicates
if channel_number in ChannelsDict.keys():
print("[ERR] duplicated channel number: {}".format(channel_number))
sys.exit(2)
ChannelsDict[channel_number] = [ name, rx_f, tx_f, rx_subtone, tx_subtone, tx_power, groups, bandwidth, modulation ]
file.close()
# reset exit_info
exit_info = None
write_channels_from_dict(ChannelsDict)
sys.exit(0)
# read and print specified chunk of blocks
def print_eeprom_blocks(start_address, end_address):
disable_radio()
for address in range(start_address,end_address):
data = get_eeprom_block(address)
hex_string = "{:03d} ".format(address) + "0x" + struct.pack('B', address).hex() + " | "
hex_string += ' '.join(struct.pack('B', x).hex() for x in data)
print(hex_string)
enable_radio()
bandplan_list = []
bp = {}
def read_eeprom_from_byte(start_byte, nbytes):
disable_radio()
data = bytearray()
sblock = start_byte//32 # from which block we should starat
sbyte = start_byte%32 # from which byte in block we should start
nblock = round(nbytes/32)+1 # how many block we need to read
# print("{} {} {}".format(sblock,sbyte,nblock))
r = 0 # readed bytes
for block in range (0, nblock):
block_data = get_eeprom_block(sblock+block) # get block
to_read = (nbytes-r)
if to_read > (32 - sbyte):
chunk_size = (32 - sbyte)
else:
chunk_size = to_read
for block_byte in range(sbyte, sbyte+chunk_size):
data.append(block_data[block_byte])
r += 1
sbyte = 0 # if there will be next block to read, we will start from first byte
return(data)
enable_radio()
def check_str_in_array(value,values_array,desc):
for s in values_array:
if s.lower() == value.lower():
return str
print("[ERR] wrong {} value '{}', allowed: {}".format(desc, value,', '.join(values_array)))
exit(2)
# decode and prints bandplan
def decode_band_plan(buf):
print("Band Plan")
print("{:15s} {:13s} {:09s} {:12s} {:14s} {:10s} {:9s}".format("Start Frequency",'End frequency','Max Power','Modulation','Bandwidth', 'Tx Allowed', 'Wrap'))
for i in range (0,20):
item = buf[(i*10):(i*10+10)]
bp['start_f'] = int.from_bytes(item[0:4], 'little')
bp['end_f'] = int.from_bytes(item[4:8], 'little')
bp['bandwidth'] = (item[9] &0b11100000) >> 5
bp['modulation'] = (item[9] &0b00011100) >> 2
bp['tx'] = (item[9] &0b00000010) >> 1
bp['wrap'] = (item[9] &0b00000001)
bp['power'] = item[8]
print ("{:15d} {:13d} {:9d} {:12s} {:14s} {:10s} {:9s}".format(
bp['start_f'],
bp['end_f'],
bp['power'],
bandplan_mod[bp['modulation']],
bandplan_bw[bp['bandwidth']],
NoYes[bp['tx']],
NoYes[bp['wrap']]
))
fm = {}
def decode_fmtuner(buf1, buf2):
print ("FM Tuner settings")
print ("{:9s} {:7s}".format("Frequency",'Band'))
for i in range (0,20):
freq_item = buf1[(i*4):(i*4+4)]
band_item = buf2[i]
fm['freq'] = int.from_bytes(freq_item[0:4], 'little')
fm['band'] = band_item
print ("{:9d} {:7s}".format(
fm['freq'],
fm_band[fm['band']],
))
sp = {}
def decode_scan_presets(buf):
print ("Scan Presets")
print ("{:15s} {:13s} {:7s} {:12s} {:5s} {:9s} {:9s} {:6s} {:10s}".format("Start Frequency",'End Frequency','Squelch','Squelch Tail','Step','Scan Hold','Scan Tail','Update','Modulation'))
for i in range (0,10):
sp_item = buf[(i*14):(i*14+14)]
sp['start_freq'] = int.from_bytes(sp_item[0:4], 'little') # 4 bytes for frequency
sp['steps'] = int.from_bytes(sp_item[4:6], 'little') # 2 bytes for scan steps
sp['squelch'] = sp_item[6] + 1; # +1 because squelch can be 1-9 (so 0-9 in byte)
sp['squelch_tail'] = sp_item[7]
sp['step'] = int.from_bytes(sp_item[8:10], 'little')
sp['scan_hold'] = sp_item[10]
sp['scan_tail'] = sp_item[11]
sp['update'] = sp_item[12]
sp['modulation'] = sp_mod[sp_item[13]]
sp['end_freq'] = sp['start_freq'] + (sp['steps'] * sp['step'])
print ("{:15d} {:13d} {:7d} {:12d} {:5} {:9d} {:9d} {:6d} {:10s}".format(
sp['start_freq'],
sp['end_freq'],
sp['squelch'],
sp['squelch_tail'],
sp['step'],
sp['scan_hold'],
sp['scan_tail'],
sp['update'],
sp['modulation'],
))
# print EEPROM content
if args.show_eeprom != False:
print_eeprom_blocks(0,255)
exit (0)
# print Band Plan
if args.show_bandplan != False:
bandplan_bytes = read_eeprom_from_byte(208*32+2,10*20)
decode_band_plan(bandplan_bytes)
sys.exit(0)
# print FM tuner channels
if args.show_fmtuner != False:
# bank 200: - squelching byte 10, HT monitoring byte 11
fm_freq_bytes = read_eeprom_from_byte(204*32,4*20) # frequency each 4 bytes
fm_band_bytes = read_eeprom_from_byte(206*32+16,1*20) # band each 1 bytes so 20 bytes starting from bank 25, byte 16
if debug:
print("fm_freq_bytes:",' '.join(struct.pack('B', x).hex() for x in fm_freq_bytes))
print("fm_band_bytes:",' '.join(struct.pack('B', x).hex() for x in fm_band_bytes))
decode_fmtuner(fm_freq_bytes,fm_band_bytes)
sys.exit(0)