-
Notifications
You must be signed in to change notification settings - Fork 0
/
puxing_px888k.py
1877 lines (1640 loc) · 66.1 KB
/
puxing_px888k.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
# Copyright 2016 Leo Barring <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from chirp import chirp_common, directory, memmap, \
bitwise, settings, errors
from struct import pack
import logging
LOG = logging.getLogger(__name__)
SUPPORT_NONSPLIT_DUPLEX_ONLY = False
SUPPORT_SPLIT_BUT_DEFAULT_TO_NONSPLIT_ALWAYS = True
UNAMBIGUOUS_CROSS_MODES_ONLY = True
# With this setting enabled, some CHIRP settings are stored in
# thought-to-be junk/padding data of the channel memories.
# Enabling this feature while using CHIRP with an actual radio
# and any effects thereof is entirely the responsibility of the user.
ENABLE_DANGEROUS_EXPERIMENTAL_FEATURES = False
MEM_FORMAT = """
// data fields are generally written 0xff if they are unset
struct {
#seekto 0x0000;
struct {
struct {
// 0-3
bbcd rx_freq[4];
// 4-7
bbcd tx_freq[4];
// 8-9 A-B
struct {
u8 digital:1,
invert:1,
high:6;
u8 low;
} tone[2];
// tx_squelch on 0, rx_squelch on 1
// C
// the duplex sign is not used for memories,
// but is kept for interface consistency
u8 duplex_sign:2,
compander:1,
txpower:1,
modulation_width:1,
txrx_reverse:1,
bcl:2;
// D
u8 scrambler_type:3,
use_scrambler:1,
opt_signal:2,
ptt_id_edge:2;
// E-F
// u8 _unknown_000E[2];
%s
} data[128];
struct {
// 0-5, alt 8-D
char entry[6];
// 6-8, alt E-F
char _unknown_0806[2];
} names[128];
#seekto 0x0c20;
bit present[128];
#seekto 0x0c30;
bit priority[128];
} channel_memory;
#seekto 0x0c00;
struct {
// 0-3
bbcd rx_freq[4];
// 4-7
bbcd tx_freq[4]; // actually offset, but kept for name consistency
// 8
struct {
u8 digital:1,
invert:1,
high:6;
u8 low;
} tone[2]; // tx_squelch on 0, rx_squelch on 1
// C
u8 duplex_sign:2,
compander:1,
txpower:1,
modulation_width:1,
txrx_reverse:1,
bcl:2;
// D
u8 scrambler_type:3,
use_scrambler:1,
opt_signal:2,
ptt_id_edge:2;
// E-F
// u8 _unknown_0C0E[2];
%s
} vfo_data[2];
#seekto 0xc40;
struct {
// 0-5
char model_string[6]; // typically PX888D, unknown if rw or ro
// 6-7
u8 _unknown_0C46[2];
// 8-9
struct {
bbcd lower_freq[2];
bbcd upper_freq[2];
} band_limits[2];
} model_information;
#seekto 0x0c50;
char radio_information_string[16];
#seekto 0x0c60;
struct {
// 0
u8 ptt_cancel_sq:1,
dis_ptt_id:1,
workmode_b:2,
use_roger_beep:1,
msk_reverse:1,
workmode_a:2;
// 1
u8 backlight_color:2,
backlight_mode:2,
dual_single_watch:1,
auto_keylock:1,
scan_mode:2;
// 2
u8 rx_stun:1,
tx_stun:1,
boot_message_mode:2,
battery_save:1,
key_beep:1,
voice_announce:2;
// 3
bbcd squelch_level;
// 4
bbcd tx_timeout;
// 5
u8 allow_keypad:1,
relay_without_disable_tail:1
_unknown_0C65:1,
call_channel_active:1,
vox_gain:4;
// 6
bbcd vox_delay;
// 7
bbcd vfo_step;
// 8
bbcd ptt_id_type;
// 9
u8 keypad_lock:1,
_unknown_0C69_1:1,
side_button_hold_mode:2,
dtmf_sidetone:1,
_unknown_0C69_2:1,
side_button_click_mode:2;
// A
u8 roger_beep:4,
main_watch:1,
_unknown_0C6A:3;
// B
u8 channel_a;
// C
u8 channel_b;
// D
u8 priority_channel;
// E
u8 wait_time;
// F
u8 _unknown_0C6F;
// 0-7 on next block
u8 _unknown_0C70[8];
// 8-D on next block
char boot_message[6];
} opt_settings;
#seekto 0x0c80;
struct {
// these fields are used for all ptt id forms (msk/dtmf/5t)
// (only one can be active and stored at a time)
// and different constraints are applied depending
// on the ptt id type
u8 entry[7];
u8 length;
} ptt_id_data[2];
// 0 is BOT, 1 is EOT
#seekto 0x0c90;
struct {
// 0
u8 _unknown_0C90;
// 1
u8 _unknown_0C91_1:3,
channel_stepping:1,
unknown_0C91_2:1
receive_range:2
unknown_0C91_3:1;
// 2-3
u8 _unknown_0C92[2];
// 4-7
u8 vfo_freq[4];
// 8-F and two more blocks
struct {
u8 entry[4];
} memory[10];
} fm_radio;
#seekto 0x0cc0;
struct {
char id_code[4];
struct {
char entry[4];
} phone_book[9];
} msk_settings;
#seekto 0x0cf0;
struct {
// 0-3
bbcd rx_freq[4];
// 4-7
bbcd tx_freq[4];
// 8
struct {
u8 digital:1,
invert:1,
high:6;
u8 low;
} tone[2];
// tx_squelch on 0, rx_squelch on 1
// C
// the duplex sign is not used for the CALL,
// channel but is kept for interface consistency
u8 duplex_sign:2,
compander:1,
txpower:1,
modulation_width:1,
txrx_reverse:1
bcl:2;
// D
u8 scrambler_type:3,
use_scrambler:1,
opt_signal:2,
ptt_id_edge:2;
// E-F
// u8 _unknown_0CFE[2];
%s
} call_channel;
#seekto 0x0d00;
struct {
// DTMF codes are stored as hex half-bytes,
// 0-9 A-D are mapped straight
// DTMF '*' is HEX E, DTMF '#' is HEX F
// 0x0d00
struct {
u8 digit_length; // 0x05 to 0x14 corresponding to 50-200ms
u8 inter_digit_pause; // same
u8 first_digit_length; // same
u8 first_digit_delay; // 0x02 to 0x14 corresponding to 100-1000ms
} timing;
#seekto 0x0d30;
u8 _unknown_0D30[2]; // 0-1
u8 group_code; // 2
u8 reset_time; // 3
u8 alert_transpond; // 4
u8 id_code[4]; // 5-8
u8 _unknown_0D39[4]; // 9-C
u8 id_code_length; // D
u8 _unknown_0d3e[2]; // E-F
// 0x0d40
u8 tx_stun_code[4];
u8 _unknown_0D44[4];
u8 tx_stun_code_length;
u8 cancel_tx_stun_code_length;
u8 cancel_tx_stun_code[4];
u8 _unknown_0D4E[2];
// 0x0d50
u8 rxtx_stun_code[4];
u8 _unknown_0D54[4];
u8 rxtx_stun_code_length;
u8 cancel_rxtx_stun_code_length;
u8 cancel_rxtx_stun_code[4];
u8 _unknown_0D4E[2];
// 0x0d60
struct {
u8 entry[5];
u8 _unknown_0D65[3];
u8 length;
u8 _unknown_0D69[7];
} phone_book[9];
} dtmf_settings;
#seekto 0x0e00;
struct {
u8 delay;
u8 _unknown_0E01[5];
u8 alert_transpond;
u8 reset_time;
u8 tone_standard;
u8 id_code[3];
#seekto 0x0e20;
struct {
u8 period;
u8 group_code:4,
repeat_code:4;
} tone_settings[4];
// the order is ZVEI1 ZVEI2 CCIR1 CCITT
#seekto 0x0e40;
// 5-Tone tone standard frequency table
// unknown use, changing the values does not seem to have
// any effect on the produced sound, but the values are not
// overwritten either.
il16 tone_frequency_table[16];
// 0xe60
u8 tx_stun_code[5];
u8 _unknown_0E65[3];
u8 tx_stun_code_length;
u8 cancel_tx_stun_code_length;
u8 cancel_tx_stun_code[5];
u8 _unknown_0E6F;
// 0xe70
u8 rxtx_stun_code[5];
u8 _unknown_0E75[3];
u8 rxtx_stun_code_length;
u8 cancel_rxtx_stun_code_length;
u8 cancel_rxtx_stun_code[5];
u8 _unknown_0E7F;
// 0xe80
struct {
u8 entry[3];
} phone_book[9];
} five_tone_settings;
} mem;"""
# various magic numbers and strings, apart from the memory format
if ENABLE_DANGEROUS_EXPERIMENTAL_FEATURES:
LOG.warn("ENABLE_DANGEROUS_EXPERIMENTAL_FEATURES"
"AND/OR DANGEROUS FEATURES ENABLED")
MEM_FORMAT = MEM_FORMAT % (
"u8 _unknown_000E_1: 6,\n"
" experimental_duplex_mode_indicator: 1,\n"
" experimental_cross_mode_indicator: 1;\n"
"u8 _unknown_000F;",
"u8 _unknown_0C0E_1: 6,\n"
" experimental_duplex_mode_indicator: 1,\n"
" experimental_cross_mode_indicator: 1;\n"
"u8 _unknown_0C0F;",
"u8 _unknown_0CFE_1: 6,\n"
" experimental_duplex_mode_indicator: 1,\n"
" experimental_cross_mode_indicator: 1;\n"
"u8 _unknown_0CFF;")
# we don't need these settings anymore, because it's exactly what the
# experimental features are about
SUPPORT_SPLIT_BUT_DEFAULT_TO_NONSPLIT_ALWAYS = False
SUPPORT_NONSPLIT_DUPLEX_ONLY = False
UNAMBIGUOUS_CROSS_MODES_ONLY = False
else:
MEM_FORMAT = MEM_FORMAT % (
"u8 _unknown_000E[2];",
"u8 _unknown_0C0E[2];",
"u8 _unknown_0CFE[2];")
FILE_MAGIC = [0xc40, 0xc50,
'\x50\x58\x38\x38\x38\x44\x00\xff'
'\x13\x40\x17\x60\x40\x00\x48\x00']
HANDSHAKE_OUT = b'XONLINE'
HANDSHAKE_IN = [b'PX888D\x00\xff']
LOWER_READ_BOUND = 0
UPPER_READ_BOUND = 0x1000
LOWER_WRITE_BOUND = 0
UPPER_WRITE_BOUND = 0x0fc0
BLOCKSIZE = 64
OFF_INT = ["Off"] + [str(x+1) for x in range(100)]
OFF_ON = ["Off", "On"]
INACTIVE_ACTIVE = ["Inactive", "Active"]
NO_YES = ["No", "Yes"]
YES_NO = ["Yes", "No"]
BANDS = [(134000000, 176000000), # VHF
(400000000, 480000000)] # UHF
SPECIAL_CHANNELS = {'VFO-A': -2, 'VFO-B': -1, 'CALL': 0}
SPECIAL_NUMBERS = {-2: 'VFO-A', -1: 'VFO-B', 0: 'CALL'}
DUPLEX_MODES = ['', '+', '-', 'split']
if SUPPORT_NONSPLIT_DUPLEX_ONLY:
DUPLEX_MODES = ['', '+', '-']
TONE_MODES = ["", "Tone", "TSQL", "DTCS", "Cross"]
CROSS_MODES = ["Tone->Tone",
"DTCS->",
"->DTCS",
"Tone->DTCS",
"DTCS->Tone",
"->Tone",
"DTCS->DTCS",
"Tone->"]
if UNAMBIGUOUS_CROSS_MODES_ONLY:
CROSS_MODES = ["Tone->Tone",
"DTCS->",
"->DTCS",
"Tone->DTCS",
"DTCS->Tone",
"->Tone",
"DTCS->DTCS"]
MODES = ["NFM", "FM"]
# Only the 'High' power level is quantified in the manual for
# the radio (4W for VHF, 5W for UHF), a web search turned
# up numbers for the 'Low' power level (0.5W for VHF and
# 0.7W for UHF), but they are not official to my knowledge
# and should be taken with a grain of salt or two.
# Numbers used in code is the averages
POWER_LEVELS = [chirp_common.PowerLevel("Low", watts=0.6),
chirp_common.PowerLevel("High", watts=4.5)]
SKIP_MODES = ["", "S"]
BCL_MODES = ["Off", "Carrier", "QT/DQT"]
SCRAMBLER_MODES = OFF_INT[0:9]
PTT_ID_EDGES = ["Off", "BOT", "EOT", "Both"]
OPTSIGN_MODES = ["None", "DTMF", "5-Tone", "MSK"]
VFO_STRIDE = ['5kHz', '6.25kHz', '10kHz', '12.5kHz', '25kHz']
AB = ['A', 'B']
WATCH_MODES = ['Single watch', 'Dual watch']
AB_MODES = ['VFO', 'Memory index', 'Memory name', 'Memory frequency']
SCAN_MODES = ["Time", "Carrier", "Seek"]
WAIT_TIMES = [("0.3s", 6), ("0.5s", 10)] +\
[("%ds" % t, t*20) for t in range(1, 13)]
BUTTON_MODES = ["Send call list data",
"Emergency alarm",
"Send 1750Hz signal",
"Open squelch"]
BOOT_MESSAGE_TYPES = ["Off", "Battery voltage", "Custom message"]
TALKBACK = ['Off', 'Chinese', 'English']
BACKLIGHT_COLORS = zip(["Blue", "Orange", "Purple"], range(1, 4))
VOX_GAIN = OFF_INT[0:10]
VOX_DELAYS = ['1s', '2s', '3s', '4s']
TRANSMIT_ALARMS = ['Off', '30s', '60s', '90s', '120s',
'150s', '180s', '210s', '240s', '270s']
DATA_MODES = ['MSK', 'DTMF', '5-Tone']
ASCIIPART = ''.join([chr(x) for x in range(0x20, 0x7f)])
DTMF = "0123456789ABCD*#"
HEXADECIMAL = "0123456789ABCDEF"
ROGER_BEEP = OFF_INT[0:11]
BACKLIGHT_MODES = ["Off", "Auto", "On"]
TONE_RESET_TIME = ['Off'] + ['%ds' % x for x in range(1, 256)]
DTMF_TONE_RESET_TIME = TONE_RESET_TIME[0:16]
DTMF_GROUPS = zip(["Off", "A", "B", "C", "D", "*", "#"], [255]+range(10, 16))
FIVE_TONE_STANDARDS = ['ZVEI1', 'ZVEI2', 'CCIR1', 'CCITT']
# should mimic the defaults in the memedit MemoryEditor somewhat
# 0 1 2 3 4 5 6 7
SANE_MEMORY_DEFAULT = b"\x14\x61\x00\x00\x14\x61\x00\x00" + \
b"\xff\xff\xff\xff\xc8\x00\xff\xff"
# 8 9 A B C D E F
# these two option sets are listed differently like this in the stock software,
# so I'm keeping them separate for now if they are in fact identical
# in behaviour, that should probably be amended
DTMF_ALERT_TRANSPOND = zip(['Off', 'Call alert',
'Transpond-alert',
'Transpond-ID code'],
[255]+range(1, 4))
FIVE_TONE_ALERT_TRANSPOND = zip(['Off', 'Alert tone',
'Transpond', 'Transpond-ID code'],
[255]+range(1, 4))
BFM_BANDS = ['87.5-108MHz', '76.0-91.0MHz', '76.0-108.0MHz', '65.0-76.0MHz']
BFM_STRIDE = ['100kHz', '50kHz']
def piperead(pipe, amount):
"""read some data, catch exceptions, validate length of data read"""
try:
d = pipe.read(amount)
except Exception as e:
raise errors.RadioError(
"Tried to read %d bytes, but got an exception: %s" %
(amount, repr(e)))
if d is None:
raise errors.RadioError(
"Tried to read %d bytes, but read operation returned <None>." %
(amount))
if d is None or len(d) != amount:
raise errors.RadioError(
"Tried to read %d bytes, but got %d bytes instead." %
(amount, len(d)))
return d
def pipewrite(pipe, data):
"""write some data, catch exceptions, validate length of data written"""
try:
n = pipe.write(data)
except Exception as e:
raise errors.RadioError(
"Tried to write %d bytes, but got an exception: %s." %
(len(data), repr(e)))
if n is None:
raise errors.RadioError(
"Tried to write %d bytes, but operation returned <None>." %
(len(data)))
if n != len(data):
raise errors.RadioError(
"Tried to write %d bytes, but wrote %d bytes instead." %
(len(data), n))
def attempt_initial_handshake(pipe):
"""try to do the initial handshake"""
pipewrite(pipe, HANDSHAKE_OUT)
x = piperead(pipe, len(HANDSHAKE_IN[0]))
if x in HANDSHAKE_IN:
return True
LOG.debug("Handshake failed: received: %s expected one of: %s" %
(repr(x), repr(HANDSHAKE_IN)))
return False
def initial_handshake(pipe, tries):
"""do an initial handshake attempt up to tries times"""
x = False
for i in range(tries):
x = attempt_initial_handshake(pipe)
if x:
break
if not x:
raise errors.RadioError("Initial handshake failed all ten tries.")
def mk_writecommand(addr):
"""makes a write command from an address specification"""
return pack('>cHc', b'W', addr, b'@')
def mk_readcommand(addr):
"""makes a read command from an address specification"""
return pack('>cHc', b'R', addr, b'@')
def expect_ack(pipe):
x = piperead(pipe, 1)
if x != b'\x06':
LOG.debug(
"Did not get ACK. received: %s, expected: '\\x06'" %
repr(x))
raise errors.RadioError("Did not get ACK when expected.")
def end_communications(pipe):
"""tell the radio that we are done"""
pipewrite(pipe, b'E')
expect_ack(pipe)
def read_block(pipe, addr):
"""read and return a chunk of data at specified address"""
r = mk_readcommand(addr)
w = mk_writecommand(addr)
pipewrite(pipe, r)
x = piperead(pipe, len(w))
if x != w:
raise errors.RadioError("Received data not following protocol.")
block = piperead(pipe, BLOCKSIZE)
return block
def write_block(pipe, addr, block):
"""write a chunk of data at specified address"""
w = mk_writecommand(addr)
pipewrite(pipe, w)
pipewrite(pipe, block)
expect_ack(pipe)
def show_progress(radio, blockaddr, upper, msg):
"""relay read/write information to the user through the gui"""
if radio.status_fn:
status = chirp_common.Status()
status.cur = blockaddr
status.max = upper
status.msg = msg
radio.status_fn(status)
def do_download(radio):
"""download from the radio to the memory map"""
initial_handshake(radio.pipe, 10)
memory = memmap.MemoryMap(b'\xff'*0x1000)
for blockaddr in range(LOWER_READ_BOUND, UPPER_READ_BOUND, BLOCKSIZE):
LOG.debug("Reading block "+str(blockaddr))
block = read_block(radio.pipe, blockaddr)
memory.set(blockaddr, block)
show_progress(radio, blockaddr, UPPER_READ_BOUND,
"Reading radio memory... %04x" % blockaddr)
end_communications(radio.pipe)
return memory
def do_upload(radio):
"""upload from the memory map to the radio"""
memory = radio.get_mmap()
initial_handshake(radio.pipe, 10)
for blockaddr in range(LOWER_WRITE_BOUND, UPPER_WRITE_BOUND, BLOCKSIZE):
LOG.debug("Writing block "+str(blockaddr))
block = memory[blockaddr:blockaddr+BLOCKSIZE]
write_block(radio.pipe, blockaddr, block)
show_progress(radio, blockaddr, UPPER_WRITE_BOUND,
"Writing radio memory... % 04x" % blockaddr)
end_communications(radio.pipe)
def parse_tone(t):
"""
parse the tone (ctss, dtcs) part of the mmap
into more easily handled data types
"""
# [ mode, value, polarity ]
if int(t.high) == 0x3f and int(t.low) == 0xff:
return [None, None, None]
elif bool(t.digital):
t = ['DTCS',
(int(t.high) & 0x0f)*100 +
((int(t.low) & 0xf0) >> 4)*10 +
(int(t.low) & 0x0f),
['N', 'R'][bool(t.invert)]]
if t[1] not in chirp_common.DTCS_CODES:
return [None, None, None]
else:
t = ['Tone',
((int(t.high) & 0xf0) >> 4)*100 +
(int(t.high) & 0x0f)*10 +
((int(t.low) & 0xf0) >> 4) +
(int(t.low) & 0x0f)/10.0,
None]
if t[1] not in chirp_common.TONES:
return [None, None, None]
return t
def unparse_tone(t):
"""parse tone data back into the format used by the radio"""
# [ mode, value, polarity ]
if t[0] == 'Tone':
tint = int(t[1]*10)
t0, tint = tint % 10, tint // 10
t1, tint = tint % 10, tint // 10
t2, tint = tint % 10, tint // 10
high = (tint << 4) | t2
low = (t1 << 4) | t0
digital = False
invert = False
return digital, invert, high, low
elif t[0] == 'DTCS':
tint = int(t[1])
t0, tint = tint % 10, tint // 10
t1, tint = tint % 10, tint // 10
high = tint
low = (t1 << 4) | t0
digital = True
invert = t[2] == 'R'
return digital, invert, high, low
return None
def decode_halfbytes(data, mapping, length):
"""
construct a string from a datatype
where each half-byte maps to a character
"""
s = ''
for i in range(length):
if i & 1 == 0:
s += mapping[(int(data[i >> 1]) & 0xf0) >> 4]
else:
s += mapping[int(data[i >> 1]) & 0x0f]
return s
def encode_halfbytes(data, datapad, mapping, fillvalue, fieldlen):
"""encode data from a string where each character maps to a half-byte"""
if len(data) & 1:
# pad to an even length
data += datapad
o = [fillvalue] * fieldlen
for i in range(0, len(data), 2):
v = (mapping.index(data[i]) << 4) | mapping.index(data[i+1])
o[i >> 1] = v
return bytearray(o)
def decode_ffstring(data):
"""decode a string delimited by 0xff"""
s = ''
for b in data:
if int(b) == 0xff:
break
s += chr(int(b))
return s
def encode_ffstring(data, fieldlen):
"""right-pad to specified length with 0xff bytes"""
extra = fieldlen-len(data)
if extra > 0:
data += '\xff'*extra
return bytearray(data)
def decode_dtmf(data, length):
"""decode a field containing dtmf data into a string"""
if length == 0xff:
return ''
return decode_halfbytes(data, DTMF, length)
def encode_dtmf(data, length, fieldlen):
"""encode a string containing dtmf characters into a data field"""
return encode_halfbytes(data, '0', DTMF, b'\xff', fieldlen)
def decode_5tone(data):
"""decode a field containing 5-tone data into a string"""
if (int(data[2]) & 0x0f) != 0:
return ''
return decode_halfbytes(data, HEXADECIMAL, 5)
def encode_5tone(data, fieldlen):
"""encode a string containing 5-tone characters into a data field"""
return encode_halfbytes(data, '0', HEXADECIMAL, b'\xff', fieldlen)
def decode_freq(data):
"""decode frequency data for the broadcast fm radio memories"""
data_out = ''
if data[0] != 0xff:
data_out = chirp_common.format_freq(
int(decode_halfbytes(data, "0123456789", len(data)))*100000)
return data_out
def encode_freq(data, fieldlen):
"""encode frequency data for the broadcast fm radio memories"""
data_out = bytearray('\xff')*fieldlen
if data != '':
data_out = encode_halfbytes((('%%0%di' % (fieldlen << 1)) %
int(chirp_common.parse_freq(data)/10)),
'', '0123456789', '', fieldlen)
return data_out
def sbyn(s, n):
"""setting by name"""
return filter(lambda x: x.get_name() == n, s)[0]
# These helper classes provide a direct link between the value
# of the widget shown in the ui, and the setting in the memory
# map of the radio, lessening the need to write large chunks
# of code, first for populating the ui from the memory map,
# then secondly for parsing the values back.
# By supplying the memory map entry to the setting instance,
# it is possible to automatically 1) initialize the value of
# the setting, as well as 2) automatically update the memory
# value when the user changes it in the ui, without adding
# any code outside the class.
class MappedIntegerSettingValue(settings.RadioSettingValueInteger):
""""
Integer setting, with the possibility to add translation
functions between memory map <-> integer setting
"""
def __init__(self, val_mem, minval, maxval, step=1,
int_from_mem=lambda x: int(x),
mem_from_int=lambda x: x,
autowrite=True):
"""
val_mem - memory map entry for the value
minval - the minimum value allowed
maxval - maximum value allowed
step - value stepping
int_from_mem - function to convert memory entry to integer
mem_from_int - function to convert integer to memory entry
autowrite - automatically write the memory map entry
when the value is changed
"""
self._val_mem = val_mem
self._int_from_mem = int_from_mem
self._mem_from_int = mem_from_int
self._autowrite = autowrite
settings.RadioSettingValueInteger.__init__(
self,
minval, maxval, self._int_from_mem(val_mem), step)
def set_value(self, x):
settings.RadioSettingValueInteger.set_value(self, x)
if self._autowrite:
self.write_mem()
def write_mem(self):
if self.get_mutable() and self._mem_from_int is not None:
self._val_mem.set_value(self._mem_from_int(
settings.RadioSettingValueInteger.get_value(self)))
class MappedListSettingValue(settings.RadioSettingValueMap):
"""Mapped list setting"""
def __init__(self, val_mem, options, autowrite=True):
"""
val_mem - memory map entry for the value
options - either a list of strings options to present,
mapped to integers 0...n
in the memory map entry, or a list of tuples
("option description", memory map value)
int_from_mem - function to convert memory entry to integer
mem_from_int - function to convert integer to memory entry
autowrite - automatically write the memory map entry when
the value is changed
"""
self._val_mem = val_mem
self._autowrite = autowrite
if not isinstance(options[0], tuple):
options = zip(options, range(len(options)))
settings.RadioSettingValueMap.__init__(
self,
options, mem_val=int(val_mem))
def set_value(self, value):
settings.RadioSettingValueMap.set_value(self, value)
if self._autowrite:
self.write_mem()
def write_mem(self):
if self.get_mutable():
self._val_mem.set_value(
settings.RadioSettingValueMap.get_mem_val(self))
class MappedCodedStringSettingValue(settings.RadioSettingValueString):
"""
generic base class for a number of mapped presented-as-strings
values which may need conversion between mem and string,
and may store a length value in a separate mem field
"""
def __init__(self, val_mem, len_mem, min_length, max_length,
charset=ASCIIPART, padchar=' ', autowrite=True,
str_from_mem=lambda mve, lve: str(mve[0:int(lve)]),
mem_val_from_str=lambda s, fl: s[0:fl],
mem_len_from_int=lambda l: l):
"""
val_mem - memory map entry for the value
len_mem - memory map entry for the length (or None)
min_length - length that the string will be right-padded to
max_length - maximum length of the string, set as maxlength
for the RadioSettingValueString
charset - the allowed charset
padchar - the character that will be used to pad short
strings, if not in the charset, charset[0] is used
autowrite - automatically call write_mem when the ui value
change
str_from_mem - function to convert from memory entry to string
value, form:
func(value_entry, length_entry or none) -> string
mem_val_from_str - function to convert from string value to
memory-fitting value, form:
func(string, value_entry_length) ->
value to store in value entry
mem_len_from_int - function to convert from string length to
memory-fitting value, form:
func(stringlength) -> value to store in length entry
"""
self._min_length = min_length
self._val_mem = val_mem
self._len_mem = len_mem
self._padchar = padchar
if padchar not in charset:
self._padchar = charset[0]
self._autowrite = autowrite
self._str_from_mem = str_from_mem
self._mem_val_from_str = mem_val_from_str
self._mem_len_from_int = mem_len_from_int
settings.RadioSettingValueString.__init__(
self,
0, max_length,
self._str_from_mem(self._val_mem, self._len_mem),
charset=charset, autopad=False)
def set_value(self, value):
"""
Set the value of the string, pad if below minimum length,
unless it's '' to provide a distinction between
uninitialized/reset data and needs-to-be-padded data
"""
while len(value) < self._min_length and len(value) != 0:
value += self._padchar
settings.RadioSettingValueString.set_value(self, value)
if self._autowrite:
self.write_mem()
def write_mem(self):
"""update the memory"""
if not self.get_mutable() or self._mem_val_from_str is None:
return
v = self.get_value()
l = len(v)
self._val_mem.set_value(self._mem_val_from_str(v, len(self._val_mem)))
if self._len_mem is not None and self._mem_len_from_int is not None:
self._len_mem.set_value(self._mem_len_from_int(l))
class MappedFFStringSettingValue(MappedCodedStringSettingValue):
"""
Mapped string setting, tailored for the puxing px888k,
which uses 0xff terminated strings.
"""
def __init__(self, val_mem, min_length, max_length,
charset=ASCIIPART, padchar=' ', autowrite=True):