baojie_bj218.py

Rick DeWitt, 02/19/2018 06:03 am

Download (46.2 kB)

 
1
# Copyright 2016:
2
# Adapted from lt725uv driver: Jim Unroe KC9HI, <rock.unroe@gmail.com>
3
# Modified for Baojie BJ-218:  2017 by Rick DeWitt (RJD), <aa0rd@yahoo.com>
4
#
5
# This program is free software: you can redistribute it and/or modify
6
# it under the terms of the GNU General Public License as published by
7
# the Free Software Foundation, either version 2 of the License, or
8
# (at your option) any later version.
9
#
10
# This program is distributed in the hope that it will be useful,
11
# but WITHOUT ANY WARRANTY; without even the implied warranty of
12
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
# GNU General Public License for more details.
14
#
15
# You should have received a copy of the GNU General Public License
16
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
17

    
18
import time
19
import struct
20
import logging
21
import re
22

    
23
LOG = logging.getLogger(__name__)
24

    
25
from chirp import chirp_common, directory, memmap
26
from chirp import bitwise, errors, util
27
from chirp.settings import RadioSettingGroup, RadioSetting, \
28
    RadioSettingValueBoolean, RadioSettingValueList, \
29
    RadioSettingValueString, RadioSettingValueInteger, \
30
    RadioSettingValueFloat,InvalidValueError, RadioSettings
31
from textwrap import dedent
32

    
33
MEM_FORMAT = """
34
#seekto 0x0200;
35
struct {
36
  u8  init_bank;
37
  u8  volume;
38
  u16 fm_freq;
39
  u8  wtled;
40
  u8  rxled;
41
  u8  txled;
42
  u8  ledsw;
43
  u8  beep;
44
  u8  ring;
45
  u8  bcl;
46
  u8  tot;
47
  u16 sig_freq;
48
  u16 dtmf_txms;
49
  u8  init_sql;
50
  u8  rptr_mode;
51
} settings;
52

    
53
#seekto 0x0240;
54
struct {
55
  u8  dtmf1_cnt;
56
  u8  dtmf1[7];
57
  u8  dtmf2_cnt;
58
  u8  dtmf2[7];
59
  u8  dtmf3_cnt;
60
  u8  dtmf3[7];
61
  u8  dtmf4_cnt;
62
  u8  dtmf4[7];
63
  u8  dtmf5_cnt;
64
  u8  dtmf5[7];
65
  u8  dtmf6_cnt;
66
  u8  dtmf6[7];
67
  u8  dtmf7_cnt;
68
  u8  dtmf7[7];
69
  u8  dtmf8_cnt;
70
  u8  dtmf8[7];
71
} dtmf_tab;
72

    
73
#seekto 0x0280;
74
struct {
75
  u8  native_id_cnt;
76
  u8  native_id_code[7];
77
  u8  master_id_cnt;
78
  u8  master_id_code[7];
79
  u8  alarm_cnt;
80
  u8  alarm_code[5];
81
  u8  id_disp_cnt;
82
  u8  id_disp_code[5];
83
  u8  revive_cnt;
84
  u8  revive_code[5];
85
  u8  stun_cnt;
86
  u8  stun_code[5];
87
  u8  kill_cnt;
88
  u8  kill_code[5];
89
  u8  monitor_cnt;
90
  u8  monitor_code[5];
91
  u8  state_now;
92
} codes;
93

    
94
#seekto 0x02d0;
95
struct {
96
  u8  hello1_cnt;
97
  char  hello1[7];
98
  u8  hello2_cnt;
99
  char  hello2[7];
100
  u32  vhf_low;
101
  u32  vhf_high;
102
  u32  uhf_low;
103
  u32  uhf_high;
104
  u8  lims_on;
105
} hello_lims;
106

    
107
struct vfo {
108
  u8  frq_chn_mode;
109
  u8  chan_num;
110
  u32 rxfreq;
111
  u16 is_rxdigtone:1,
112
      rxdtcs_pol:1,
113
      rx_tone:14;
114
  u8  rx_mode;
115
  u8  unknown_ff;
116
  u16 is_txdigtone:1,
117
      txdtcs_pol:1,
118
      tx_tone:14;
119
  u8  launch_sig;
120
  u8  tx_end_sig;
121
  u8  power;
122
  u8  fm_bw;
123
  u8  cmp_nder;
124
  u8  scrm_blr;
125
  u8  shift;
126
  u32 offset;
127
  u16 step;
128
  u8  sql;
129
};
130

    
131
#seekto 0x0300;
132
struct {
133
  struct vfo vfoa;
134
} upper;
135

    
136
#seekto 0x0380;
137
struct {
138
  struct vfo vfob;
139
} lower;
140

    
141
struct mem {
142
  u32 rxfreq;
143
  u16 is_rxdigtone:1,
144
      rxdtcs_pol:1,
145
      rxtone:14;
146
  u8  recvmode;
147
  u32 txfreq;
148
  u16 is_txdigtone:1,
149
      txdtcs_pol:1,
150
      txtone:14;
151
  u8  botsignal;
152
  u8  eotsignal;
153
  u8  power:1,
154
      wide:1,
155
      compandor:1
156
      scrambler:1
157
      unknown:4;
158
  u8  namelen;
159
  u8  name[7];
160
};
161

    
162
#seekto 0x0400;
163
struct mem upper_memory[128];
164

    
165
#seekto 0x1000;
166
struct mem lower_memory[128];
167

    
168
#seekto 0x1C00;
169
struct {
170
  char  mod_num[6];
171
} mod_id;
172

    
173
"""
174

    
175
MEM_SIZE = 0x1C00
176
BLOCK_SIZE = 0x40                # 'Standard' 24-byte block
177
STIMEOUT = 2
178

    
179
LIST_RECVMODE = ["QT/DQT", "QT/DQT + Signaling"]
180
LIST_SIGNAL = ["Off"] + ["DTMF%s" % x for x in range(1, 9)] + \
181
              ["DTMF%s + Identity" % x for x in range(1, 9)] + \
182
              ["Identity code"]
183
LIST_POWER = ["Low",  "High"]               
184
LIST_COLOR = ["Off", "Orange", "Blue", "Purple"]
185
LIST_LEDSW = ["Auto", "On"]
186
LIST_RING = ["Off"] + ["%s" % x for x in range(1, 10)]
187
LIST_TDR_DEF = ["A-Upper", "B-Lower"]
188
LIST_TIMEOUT = ["Off"] + ["%s" % x for x in range(30, 630, 30)]
189
LIST_VFOMODE = ["Frequency Mode", "Channel Mode"]
190
TONES_CTCSS =  sorted(chirp_common.TONES)        # RJD: Numeric, Defined in \chirp\chirp_common.py
191
LIST_CTCSS = ["Off"] +[str(x) for x in TONES_CTCSS]            # Converted to strings
192
    #  Now append the DxxxN and DxxxI DTCS codes from chirp_common
193
for x in chirp_common.DTCS_CODES:
194
    LIST_CTCSS.append("D{:03d}N".format(x))
195
for x in chirp_common.DTCS_CODES:
196
    LIST_CTCSS.append("D{:03d}R".format(x))
197
LIST_BW= ["Narrow", "Wide"]
198
LIST_SHIFT= ["Off"," + ", " - "]
199
STEPS = [2.5, 5.0, 6.25, 10.0, 12.5, 20.0, 25.0, 50.0]
200
LIST_STEPS = [str(x) for x in STEPS]
201
LIST_STATE = ["Normal", "Stun", "Kill"]
202
LIST_SSF =  ["1000", "1450", "1750", "2100"]
203
LIST_DTMFTX= ["50", "100", "150", "200", "300","500"]
204

    
205
SETTING_LISTS = {
206
"init_bank": LIST_TDR_DEF ,
207
"tot": LIST_TIMEOUT,
208
"wtled": LIST_COLOR,
209
"rxled": LIST_COLOR,
210
"txled": LIST_COLOR,
211
"sig_freq": LIST_SSF,
212
"dtmf_txms": LIST_DTMFTX,
213
"ledsw": LIST_LEDSW,
214
"frq_chn_mode": LIST_VFOMODE,
215
"rx_tone": LIST_CTCSS,
216
"tx_tone": LIST_CTCSS,
217
"rx_mode": LIST_RECVMODE,
218
"launch_sig": LIST_SIGNAL,
219
"tx_end_sig": LIST_SIGNAL,
220
"power": LIST_POWER,
221
"fm_bw": LIST_BW,
222
"shift": LIST_SHIFT,
223
"step": LIST_STEPS,
224
"ring": LIST_RING,
225
"state_now": LIST_STATE
226
}
227

    
228
def _clean_buffer(radio):
229
    radio.pipe.timeout = 0.005
230
    junk = radio.pipe.read(256)
231
    radio.pipe.timeout = STIMEOUT
232
    if junk:
233
        Log.debug("Got %i bytes of junk before starting" % len(junk))
234

    
235

    
236
def _rawrecv(radio, amount):
237
    """Raw read from the radio device"""
238
    data = ""
239
    try:
240
        data = radio.pipe.read(amount)
241
    except:
242
        _exit_program_mode(radio)
243
        msg = "Generic error reading data from radio; check your cable."
244
        raise errors.RadioError(msg)
245

    
246
    if len(data) != amount:
247
        _exit_program_mode(radio)
248
        msg = "Error reading data from radio: not the amount of data we want."
249
        raise errors.RadioError(msg)
250

    
251
    return data
252

    
253

    
254
def _rawsend(radio, data):
255
    """Raw send to the radio device"""
256
    try:
257
        radio.pipe.write(data)
258
    except:
259
        raise errors.RadioError("Error sending data to radio")
260

    
261

    
262
def _make_frame(cmd, addr, length, data=""):
263
    """Pack the info in the header format"""
264
    frame = struct.pack(">4sHH", cmd, addr, length)
265
    # add the data if set
266
    if len(data) != 0:
267
        frame += data
268
    # return the data
269
    return frame
270

    
271

    
272
def _recv(radio, addr, length):
273
    """Get data from the radio """
274

    
275
    data = _rawrecv(radio, length)
276

    
277
    # DEBUG
278
    LOG.info("Response:")
279
    LOG.debug(util.hexprint(data))
280

    
281
    return data
282

    
283

    
284
def _do_ident(radio):
285
    """Put the radio in PROGRAM mode & identify it"""
286
    #  set the serial discipline
287
    radio.pipe.baudrate = 19200
288
    radio.pipe.parity = "N"
289
    radio.pipe.timeout = STIMEOUT
290

    
291
    # flush input buffer
292
    _clean_buffer(radio)
293

    
294
    magic = "PROM_LIN"
295

    
296
    _rawsend(radio, magic)
297

    
298
    ack = _rawrecv(radio, 1)
299
    if ack != "\x06":
300
        _exit_program_mode(radio)
301
        if ack:
302
            LOG.debug(repr(ack))
303
        raise errors.RadioError("Radio did not respond")
304

    
305
    return True
306

    
307

    
308
def _exit_program_mode(radio):
309
    endframe = "EXIT"
310
    _rawsend(radio, endframe)
311

    
312

    
313
def _download(radio):
314
    """Get the memory map"""
315

    
316
    # put radio in program mode and identify it
317
    _do_ident(radio)
318

    
319
    # UI progress
320
    status = chirp_common.Status()
321
    status.cur = 0
322
    status.max = MEM_SIZE / BLOCK_SIZE
323
    status.msg = "Cloning from radio..."
324
    radio.status_fn(status)
325

    
326
    data = ""
327
    for addr in range(0, MEM_SIZE, BLOCK_SIZE):
328
        frame = _make_frame("READ", addr, BLOCK_SIZE)
329
        # DEBUG
330
        LOG.info("Request sent:")
331
        LOG.debug(util.hexprint(frame))
332

    
333
        # sending the read request
334
        _rawsend(radio, frame)
335

    
336
        # now we read
337
        d = _recv(radio, addr, BLOCK_SIZE)
338

    
339
        # aggregate the data
340
        data += d
341

    
342
        # UI Update
343
        status.cur = addr / BLOCK_SIZE
344
        status.msg = "Cloning from radio..."
345
        radio.status_fn(status)
346

    
347
    _exit_program_mode(radio)
348

    
349
  #   data += "LT-725UV"
350
    data +=  "BJ-218"                        # Append model number to memory map. RJD
351

    
352
    return data
353

    
354

    
355
def _upload(radio):
356
    """Upload procedure"""
357

    
358
    # put radio in program mode and identify it
359
    _do_ident(radio)
360

    
361
    # UI progress
362
    status = chirp_common.Status()
363
    status.cur = 0
364
    status.max = MEM_SIZE / BLOCK_SIZE
365
    status.msg = "Cloning to radio..."
366
    radio.status_fn(status)
367

    
368
    # the fun starts here
369
    for addr in range(0, MEM_SIZE, BLOCK_SIZE):
370
        # sending the data
371
        data = radio.get_mmap()[addr:addr + BLOCK_SIZE]
372

    
373
        frame = _make_frame("WRIE", addr, BLOCK_SIZE, data)
374

    
375
        _rawsend(radio, frame)
376

    
377
        # receiving the response
378
        ack = _rawrecv(radio, 1)
379
        if ack != "\x06":
380
            _exit_program_mode(radio)
381
            msg = "Bad ack writing block 0x%04x" % addr
382
            raise errors.RadioError(msg)
383

    
384
        # UI Update
385
        status.cur = addr / BLOCK_SIZE
386
        status.msg = "Cloning to radio..."
387
        radio.status_fn(status)
388

    
389
    _exit_program_mode(radio)
390

    
391

    
392
def model_match(cls, data):
393
    """Match the opened/downloaded image to the correct version"""
394
 #   rid = data[0x1C00:0x1C08]       # LT-725UV
395
    rid = data[0x1C00:0x1C06]                    # BJ-218  RJD
396

    
397
    if rid == cls.MODEL:
398
        return True
399

    
400
    return False
401

    
402

    
403
def _split(rf, f1, f2):
404
    """Returns False if the two freqs are in the same band (no split)
405
    or True otherwise"""
406

    
407
    # determine if the two freqs are in the same band
408
    for low, high in rf.valid_bands:
409
        if f1 >= low and f1 <= high and \
410
                f2 >= low and f2 <= high:
411
            # if the two freqs are on the same Band this is not a split
412
            return False
413

    
414
    # if you get here is because the freq pairs are split
415
    return True
416

    
417
class Luiton(chirp_common.Alias):
418
    VENDOR = "Luiton"
419
    MODEL = "LT-725UV"
420

    
421
class Zastone(chirp_common.Alias):
422
    VENDOR = "Zastone"
423
    MODEL = "BJ-218"
424

    
425
class Hesenate(chirp_common.Alias):
426
    VENDOR = "Hesenate"
427
    MODEL = "BJ-218"
428

    
429
@directory.register
430
class BJ218(chirp_common.CloneModeRadio,
431
              chirp_common.ExperimentalRadio):
432
    """Baojie BJ-218 Rad000000io"""
433
    VENDOR = "Baojie"
434
    MODEL = "BJ-218"
435
    MODES = ["NFM", "FM"]
436
    POWER_LEVELS = [chirp_common.PowerLevel("High", watts=30.00),
437
        chirp_common.PowerLevel("Low",  watts=5.00)]   
438
    TONES = chirp_common.TONES
439
    DTCS_CODES = sorted(chirp_common.DTCS_CODES + [645])
440
#    NAME_LENGTH = 6              #LT-725UV
441
    NAME_LENGTH = 7                           # BJ-218
442
    DTMF_CHARS = list("0123456789ABCD*#")
443

    
444
    VALID_BANDS = [(136000000, 176000000),
445
                   (400000000, 480000000)]
446

    
447
    # valid chars on the LCD
448
    VALID_CHARS = chirp_common.CHARSET_ALPHANUMERIC + \
449
        "`{|}!\"#$%&'()*+,-./:;<=>?@[]^_"
450

    
451
    ALIASES = [Luiton, Zastone, Hesenate]
452

    
453
    @classmethod
454
    def get_prompts(cls):
455
        rp = chirp_common.RadioPrompts()
456
        rp.experimental = \
457
            ('The BJ-218 driver is a beta version.\n'
458
             '\n'
459
             'Please save an unedited copy of your first successful\n'
460
             'download to a CHIRP Radio Images(*.img) file.'
461
             )
462
        rp.pre_download = _(dedent("""\
463
            Follow this instructions to download your info:
464

    
465
            1 - Turn off your radio
466
            2 - Connect your interface cable
467
            3 - Turn on your radio
468
            4 - Do the download of your radio data
469
            5 - Turn off your radio
470
            6 - Unplug the interface cable
471
            """))
472

    
473
        rp.pre_upload = _(dedent("""\
474
            Follow this instructions to upload your info:
475

    
476
            1 - Turn off your radio
477
            2 - Connect your interface cable
478
            3 - Turn on your radio
479
            4 - Do the upload of your radio data
480
            5 - Turn off your radio
481
            6 - Unplug the interface cable
482
            """))
483
        return rp
484

    
485

    
486
    def get_features(self):
487
        rf = chirp_common.RadioFeatures()
488
        rf.has_settings = True
489
        rf.has_bank = False
490
        rf.has_tuning_step = False
491
        rf.can_odd_split = True
492
        rf.has_name = True
493
        rf.has_offset = True
494
        rf.has_mode = True
495
        rf.has_dtcs = True
496
        rf.has_rx_dtcs = True
497
        rf.has_dtcs_polarity = True
498
        rf.has_ctone = True
499
        rf.has_cross = True
500
        rf.has_sub_devices = self.VARIANT == ""
501
        rf.valid_modes = self.MODES
502
        rf.valid_characters = self.VALID_CHARS
503
        rf.valid_duplexes = ["", "-", "+", "split", "off"]
504
        rf.valid_tmodes = ['', 'Tone', 'TSQL', 'DTCS', 'Cross']
505
        rf.valid_cross_modes = [
506
            "Tone->Tone",
507
            "DTCS->",
508
            "->DTCS",
509
            "Tone->DTCS",
510
            "DTCS->Tone",
511
            "->Tone",
512
            "DTCS->DTCS"]
513
        rf.valid_skips = []
514
        rf.valid_power_levels = self.POWER_LEVELS 
515
        rf.valid_name_length = self.NAME_LENGTH
516
        rf.valid_dtcs_codes = self.DTCS_CODES
517
        rf.valid_bands = self.VALID_BANDS
518
        rf.memory_bounds = (1, 128)
519
        return rf
520

    
521
    def get_sub_devices(self):
522
        return [BJ218Upper(self._mmap), BJ218Lower(self._mmap)]
523

    
524
    def sync_in(self):
525
        """Download from radio"""
526
        try:
527
            data = _download(self)
528
        except errors.RadioError:
529
            # Pass through any real errors we raise
530
            raise
531
        except:
532
            # If anything unexpected happens, make sure we raise
533
            # a RadioError and log the problem
534
            LOG.exception('Unexpected error during download')
535
            raise errors.RadioError('Unexpected error communicating '
536
                                    'with the radio')
537
        self._mmap = memmap.MemoryMap(data)
538
        self.process_mmap()
539

    
540
    def sync_out(self):
541
        """Upload to radio"""
542
        try:
543
            _upload(self)
544
        except:
545
            # If anything unexpected happens, make sure we raise
546
            # a RadioError and log the problem
547
            LOG.exception('Unexpected error during upload')
548
            raise errors.RadioError('Unexpected error communicating '
549
                                    'with the radio')
550

    
551
    def process_mmap(self):
552
        """Process the mem map into the mem object"""
553
        self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
554

    
555
    def get_raw_memory(self, number):
556
        if (self._vfo == "upper"):            # For some reason the _memory_obj() call fails
557
            return repr(self._memobj.upper_memory[number - 1])
558
        else :
559
            return repr(self._memobj.lower_memory[number - 1])
560

    
561
    def _memory_obj(self, suffix=""):
562
        return getattr(self._memobj, "%s_memory%s" % (self._vfo, suffix))
563

    
564
    def _get_dcs(self, val):
565
        return int(str(val)[2:-18])
566

    
567
    def _set_dcs(self, val):
568
        return int(str(val), 16)
569

    
570
    def get_memory(self, number):
571
        _mem = self._memory_obj()[number - 1]
572

    
573
        mem = chirp_common.Memory()
574
        mem.number = number
575

    
576
        if _mem.get_raw()[0] == "\xff":
577
            mem.empty = True
578
            return mem
579

    
580
        mem.freq = int(_mem.rxfreq) * 10
581

    
582
        if _mem.txfreq == 0xFFFFFFFF:
583
            # TX freq not set
584
            mem.duplex = "off"
585
            mem.offset = 0
586
        elif int(_mem.rxfreq) == int(_mem.txfreq):
587
            mem.duplex = ""
588
            mem.offset = 0
589
        elif _split(self.get_features(), mem.freq, int(_mem.txfreq) * 10):
590
            mem.duplex = "split"
591
            mem.offset = int(_mem.txfreq) * 10
592
        else:
593
            mem.duplex = int(_mem.rxfreq) > int(_mem.txfreq) and "-" or "+"
594
            mem.offset = abs(int(_mem.rxfreq) - int(_mem.txfreq)) * 10
595

    
596
        for char in _mem.name[:_mem.namelen]:
597
            mem.name += chr(char)
598

    
599
        dtcs_pol = ["N", "N"]
600

    
601
        if _mem.rxtone == 0x3FFF:
602
            rxmode = ""
603
        elif _mem.is_rxdigtone == 0:
604
            # ctcss
605
            rxmode = "Tone"
606
            mem.ctone = int(_mem.rxtone) / 10.0
607
        else:
608
            # digital
609
            rxmode = "DTCS"
610
            mem.rx_dtcs = self._get_dcs(_mem.rxtone)
611
            if _mem.rxdtcs_pol == 1:
612
                dtcs_pol[1] = "R"
613

    
614
        if _mem.txtone == 0x3FFF:
615
            txmode = ""
616
        elif _mem.is_txdigtone == 0:
617
            # ctcss
618
            txmode = "Tone"
619
            mem.rtone = int(_mem.txtone) / 10.0
620
        else:
621
            # digital
622
            txmode = "DTCS"
623
            mem.dtcs = self._get_dcs(_mem.txtone)
624
            if _mem.txdtcs_pol == 1:
625
                dtcs_pol[0] = "R"
626

    
627
        if txmode == "Tone" and not rxmode:
628
            mem.tmode = "Tone"
629
        elif txmode == rxmode and txmode == "Tone" and mem.rtone == mem.ctone:
630
            mem.tmode = "TSQL"
631
        elif txmode == rxmode and txmode == "DTCS" and mem.dtcs == mem.rx_dtcs:
632
            mem.tmode = "DTCS"
633
        elif rxmode or txmode:
634
            mem.tmode = "Cross"
635
            mem.cross_mode = "%s->%s" % (txmode, rxmode)
636

    
637
        mem.dtcs_polarity = "".join(dtcs_pol)
638

    
639
        mem.mode = self.MODES[_mem.wide]
640

    
641
  #      val = _mem.power                            # RJD
642
  #      if _mem.power == 1:                      # BJ-218 memory only supports low / high
643
  #          val = 2                                               # bit 1 off/on
644
 #       mem.power = LIST_POWER[val]         # RJD
645

    
646
        return mem
647

    
648
    def set_memory(self, mem):
649
        _mem = self._memory_obj()[mem.number - 1]
650

    
651
        if mem.empty:
652
            _mem.set_raw("\xff" * 24)
653
            _mem.namelen = 0
654
            return
655

    
656
        _mem.set_raw("\xFF" * 15 + "\x00\x00" + "\xFF" * 7)
657

    
658
        _mem.rxfreq = mem.freq / 10
659
        if mem.duplex == "off":
660
            _mem.txfreq = 0xFFFFFFFF
661
        elif mem.duplex == "split":
662
            _mem.txfreq = mem.offset / 10
663
        elif mem.duplex == "+":
664
            _mem.txfreq = (mem.freq + mem.offset) / 10
665
        elif mem.duplex == "-":
666
            _mem.txfreq = (mem.freq - mem.offset) / 10
667
        else:
668
            _mem.txfreq = mem.freq / 10
669

    
670
        _mem.namelen = len(mem.name)
671
        _namelength = self.get_features().valid_name_length
672
        for i in range(_namelength):
673
            try:
674
                _mem.name[i] = ord(mem.name[i])
675
            except IndexError:
676
                _mem.name[i] = 0xFF
677

    
678
        rxmode = ""
679
        txmode = ""
680

    
681
        if mem.tmode == "Tone":
682
            txmode = "Tone"
683
        elif mem.tmode == "TSQL":
684
            rxmode = "Tone"
685
            txmode = "TSQL"
686
        elif mem.tmode == "DTCS":
687
            rxmode = "DTCSSQL"
688
            txmode = "DTCS"
689
        elif mem.tmode == "Cross":
690
            txmode, rxmode = mem.cross_mode.split("->", 1)
691

    
692
        if rxmode == "":
693
            _mem.rxdtcs_pol = 1
694
            _mem.is_rxdigtone = 1
695
            _mem.rxtone = 0x3FFF
696
        elif rxmode == "Tone":
697
            _mem.rxdtcs_pol = 0
698
            _mem.is_rxdigtone = 0
699
            _mem.rxtone = int(mem.ctone * 10)
700
        elif rxmode == "DTCSSQL":
701
            _mem.rxdtcs_pol = 1 if mem.dtcs_polarity[1] == "R" else 0
702
            _mem.is_rxdigtone = 1
703
            _mem.rxtone = self._set_dcs(mem.dtcs)
704
        elif rxmode == "DTCS":
705
            _mem.rxdtcs_pol = 1 if mem.dtcs_polarity[1] == "R" else 0
706
            _mem.is_rxdigtone = 1
707
            _mem.rxtone = self._set_dcs(mem.rx_dtcs)
708

    
709
        if txmode == "":
710
            _mem.txdtcs_pol = 1
711
            _mem.is_txdigtone = 1
712
            _mem.txtone = 0x3FFF
713
        elif txmode == "Tone":
714
            _mem.txdtcs_pol = 0
715
            _mem.is_txdigtone = 0
716
            _mem.txtone = int(mem.rtone * 10)
717
        elif txmode == "TSQL":
718
            _mem.txdtcs_pol = 0
719
            _mem.is_txdigtone = 0
720
            _mem.txtone = int(mem.ctone * 10)
721
        elif txmode == "DTCS":
722
            _mem.txdtcs_pol = 1 if mem.dtcs_polarity[0] == "R" else 0
723
            _mem.is_txdigtone = 1
724
            _mem.txtone = self._set_dcs(mem.dtcs)
725

    
726
        _mem.wide = self.MODES.index(mem.mode)
727
 #       if mem.power== 0: _mem.power = 0
728
  #      else: _mem.power= 1             # 'Mid' not allowed, set to high
729

    
730

    
731
    def get_settings(self):
732
        """Translate the bit in the mem_struct into settings in the UI"""
733
        _sets = self._memobj.settings                         # define mem struct write-back shortcuts
734
        _vfoa = self._memobj.upper.vfoa
735
        _vfob = self._memobj.lower.vfob
736
        _lims = self._memobj.hello_lims
737
        _codes = self._memobj.codes
738
        _dtmf = self._memobj.dtmf_tab
739

    
740
        basic = RadioSettingGroup("basic", "Basic Settings")
741
        a_band = RadioSettingGroup("a_band", "VFO A-Upper Settings")    # RJD
742
        b_band = RadioSettingGroup("b_band", "VFO B-Lower Settings")    # RJD
743
        codes = RadioSettingGroup("codes", "Codes & DTMF Groups")    # RJD
744
        lims = RadioSettingGroup("lims", "PowerOn & Freq Limits")    # RJD
745
        group = RadioSettings(basic, a_band, b_band, lims, codes)    # RJD
746

    
747
        # Basic Settings
748
        bnd_mode = RadioSetting("settings.init_bank", "TDR Band Default",
749
                            RadioSettingValueList(LIST_TDR_DEF, LIST_TDR_DEF[ _sets.init_bank]))
750
        basic.append(bnd_mode)
751

    
752
        volume = RadioSetting("settings.volume", "Volume",
753
                              RadioSettingValueInteger(0, 20,
754
                                  _sets.volume))
755
        basic.append(volume)
756

    
757
        def my_word2raw(setting, obj, atrb, mlt=10):              # < Callback: convert UI floating value 131.8 to 16b int 1318
758
  #          LOG.warning("Setting: "+str(setting))
759
            if str( setting.value) == "Off": 
760
               frq= 0x0FFFF
761
            else:
762
                frq=int(float(str(setting.value)) * float(mlt))
763
            if frq == 0 : frq = 0xFFFF
764
  #          LOG.warning("Word2raw Frq= "+str(frq))
765
            setattr(obj, atrb, frq)
766
            return
767

    
768
        def my_adjraw(setting, obj, atrb, fix):        # < Callback: add or subtract fix from value
769
   #         LOG.warning("Setting: "+str(setting))
770
            vx = int(str(setting.value))
771
            value = vx  + int(fix)
772
            if value<0: value = 0
773
            if atrb == "frq_chn_mode" and int(str(setting.value))==2: 
774
                value =  vx *2           # special handling for frq_chn_mode; 2 => 1
775
            setattr(obj, atrb, value)
776
            return
777

    
778
        def my_dbl2raw(setting, obj, atrb, flg=1):     # < Callback: convert from freq 146.7600 to 14760000 U32
779
            vr = float(str(setting.value))
780
            value = vr * 100000
781
            if flg ==1 and value == 0: value = 0xFFFFFFFF      # flg=1 means 0 becomes ff, else leave as possible 0
782
            setattr(obj, atrb, value)
783
            return
784

    
785
        def my_val_list(setting, obj, atrb):            # < Callback: from ValueList with non-sequential, actual values
786
            value = int(str(setting.value))            # get the integer value
787
  #          LOG.warning("Val from List: "+str(value))
788
            if atrb == "tot": value = int(value/30)    # 30 second increments
789
            setattr(obj, atrb, value)
790
            return
791

    
792
        def my_spcl(setting,obj, atrb):        # < Callback: Special handling based on atrb
793
            if atrb == "frq_chn_mode":
794
                idx = LIST_VFOMODE.index (str(setting.value))                # returns 0 or 1
795
                value = idx * 2            # set bit 1
796
            setattr(obj, atrb, value)
797
            return
798

    
799
        def my_tone_strn(obj, is_atr, pol_atr, tone_atr):        # generate the CTCS/DCS tone code string
800
            vx = int(getattr(obj,tone_atr))
801
 #           LOG.warning("Vx= "+str(vx))
802
            if vx == 16383 or vx== 0: return "Off"                 # 16383 is all bits set
803
            if getattr(obj,is_atr) ==0:             # Simple CTCSS code
804
                tstr = str(vx/10.0)
805
            else:        # DCS
806
                if getattr(obj,pol_atr)== 0: tstr = "D{:03x}R".format(vx)
807
                else: tstr = "D{:03x}N".format(vx)
808
   #         LOG.warning("Tone String: "+tstr)
809
            return tstr
810

    
811
        def my_set_tone(setting, obj, is_atr, pol_atr, tone_atr):
812
#       < Callback- create the tone setting from string code
813
            sx = str(setting.value)                   # '131.8'  or 'D231N' or 'Off'
814
            if sx == "Off":
815
                isx = 1
816
                polx = 1
817
                tonx = 0x3FFF
818
            elif sx[0]=="D":         # DCS
819
                isx = 1
820
                if sx[4]=="N": polx=1
821
                else: polx=0
822
                tonx = int(sx[1:4],16)
823
            else:                                     # CTCSS
824
                isx = 0
825
                polx = 0
826
                tonx = int(float(sx)*10.0)
827
    #        LOG.warning("Setting tone: is="+str(isx)+", pol="+str(polx)+", tone="+hex(tonx))
828
            setattr(obj,is_atr,isx)
829
            setattr(obj,pol_atr,polx)
830
            setattr(obj,tone_atr,tonx)
831
            return
832

    
833
        val = _sets.fm_freq /10.0
834
        if val == 0 : val = 88.9            # 0 is not valid
835
        rs = RadioSetting("settings.fm_freq", "FM Broadcast Freq (MHz)",
836
                          RadioSettingValueFloat(65, 108.0,val, 0.1, 1))
837
        rs.set_apply_callback(my_word2raw, _sets, "fm_freq")
838
        basic.append(rs)
839

    
840
        wtled = RadioSetting("wtled", "Standby LED Color",
841
                             RadioSettingValueList(LIST_COLOR, LIST_COLOR[
842
                                 _sets.wtled]))
843
        basic.append(wtled)
844

    
845
        rxled = RadioSetting("rxled", "RX LED Color",
846
                             RadioSettingValueList(LIST_COLOR, LIST_COLOR[
847
                                 _sets.rxled]))
848
        basic.append(rxled)
849

    
850
        txled = RadioSetting("txled", "TX LED Color",
851
                             RadioSettingValueList(LIST_COLOR, LIST_COLOR[
852
                                 _sets.txled]))
853
        basic.append(txled)
854

    
855
        ledsw = RadioSetting("ledsw", "Back light mode",
856
                             RadioSettingValueList(LIST_LEDSW, LIST_LEDSW[
857
                                 _sets.ledsw]))
858
        basic.append(ledsw)
859

    
860
        beep = RadioSetting("settings.beep", "Beep",
861
                            RadioSettingValueBoolean(bool(_sets.beep)))
862
        basic.append(beep)
863

    
864
        ring = RadioSetting("ring", "Ring (Secs)",
865
                            RadioSettingValueList(LIST_RING, LIST_RING[
866
                                _sets.ring]))
867
        basic.append(ring)
868

    
869
        bcl = RadioSetting("settings.bcl", "Busy channel lockout",
870
                           RadioSettingValueBoolean(bool(_sets.bcl)))
871
        basic.append(bcl)
872

    
873
        tmp = str(int(_sets.tot)*30)        # _sets.tot has 30 sec step counter
874
        rs = RadioSetting("settings.tot", "Transmit Timeout (Secs)",
875
                           RadioSettingValueList(LIST_TIMEOUT, tmp))
876
        rs.set_apply_callback(my_val_list, _sets, "tot")
877
        basic.append(rs)
878
                
879
        tmp =str(int( _sets.sig_freq))
880
        rs = RadioSetting("settings.sig_freq", "Single Signaling Tone (Htz)",
881
                           RadioSettingValueList(LIST_SSF,tmp))
882
        rs.set_apply_callback(my_val_list, _sets, "sig_freq")
883
        basic.append(rs)
884

    
885
        tmp =str(int( _sets.dtmf_txms))
886
        rs = RadioSetting("settings.dtmf_txms", "DTMF Tx Duration (mSecs)",
887
                           RadioSettingValueList(LIST_DTMFTX, tmp))
888
        rs.set_apply_callback(my_val_list, _sets, "dtmf_txms")
889
        basic.append(rs)
890

    
891
        if _sets.init_sql == 0xFF:
892
            val = 0x04
893
        else:
894
            val = _sets.init_sql
895

    
896
        rs = RadioSetting("settings.init_sql", "Squelch",RadioSettingValueInteger(0, 9, val))
897
        basic.append(rs)
898

    
899
        rs = RadioSetting("settings.rptr_mode", "Repeater Mode",
900
                           RadioSettingValueBoolean(bool(_sets.rptr_mode)))
901
        basic.append(rs)
902

    
903
    # UPPER BAND SETTINGS    RJD
904

    
905
        val = _vfoa.frq_chn_mode/2            # Freq Mode, convert bit 1 state to index pointer 
906
        rs = RadioSetting("upper.vfoa.frq_chn_mode", "Default Mode",
907
                              RadioSettingValueList(LIST_VFOMODE, LIST_VFOMODE[val]))
908
        rs.set_apply_callback(my_spcl,_vfoa,"frq_chn_mode")        # special handling
909
        a_band.append(rs)
910

    
911
        val =_vfoa.chan_num+1                  # add 1 for 1-128 displayed
912
        rs = RadioSetting("upper.vfoa.chan_num", "Initial Chan", RadioSettingValueInteger(1, 128, val))
913
        rs.set_apply_callback(my_adjraw,_vfoa,"chan_num",-1)
914
        a_band.append(rs)
915

    
916
        val  = _vfoa.rxfreq /100000.0 
917
        rs = RadioSetting("upper.vfoa.rxfreq ", "Default Recv Freq (MHz)",
918
                          RadioSettingValueFloat(136.0, 176.0,val, 0.001,5))
919
        rs.set_apply_callback(my_dbl2raw,_vfoa,"rxfreq")
920
        a_band.append(rs)
921

    
922
        tmp = my_tone_strn(_vfoa, "is_rxdigtone", "rxdtcs_pol", "rx_tone")
923
        rs = RadioSetting("rx_tone", "Default Recv CTCSS (Htz)",
924
                              RadioSettingValueList(LIST_CTCSS,tmp))
925
        rs.set_apply_callback(my_set_tone,_vfoa,"is_rxdigtone", "rxdtcs_pol", "rx_tone")
926
        a_band.append(rs)
927

    
928
        rs = RadioSetting("upper.vfoa.rx_mode", "Default Recv Mode",
929
                              RadioSettingValueList(LIST_RECVMODE,LIST_RECVMODE[_vfoa.rx_mode]))
930
        a_band.append(rs)
931

    
932
        tmp = my_tone_strn(_vfoa, "is_txdigtone", "txdtcs_pol", "tx_tone")
933
        rs = RadioSetting("tx_tone", "Default Xmit CTCSS (Htz)",
934
                              RadioSettingValueList(LIST_CTCSS,tmp))
935
        rs.set_apply_callback(my_set_tone,_vfoa,"is_txdigtone", "txdtcs_pol", "tx_tone")
936
        a_band.append(rs)
937

    
938
        rs = RadioSetting("upper.vfoa.launch_sig", "Launch Signaling",
939
                              RadioSettingValueList(LIST_SIGNAL,LIST_SIGNAL[_vfoa.launch_sig]))
940
        a_band.append(rs)
941

    
942
        rs = RadioSetting("upper.vfoa.tx_end_sig", "Xmit End Signaling",
943
                              RadioSettingValueList(LIST_SIGNAL,LIST_SIGNAL[_vfoa.tx_end_sig]))
944
        a_band.append(rs)
945

    
946
        val =  _vfoa.power / 2           # Bit 1 is set (High) or cleared (low)
947
        rs = RadioSetting("upper.vfoa.power", "Bank Power",
948
                              RadioSettingValueList(LIST_POWER, LIST_POWER[val]))
949
        a_band.append(rs)
950

    
951
        rs = RadioSetting("upper.vfoa.fm_bw", "Wide/Narrow Band",
952
                              RadioSettingValueList(LIST_BW,LIST_BW[_vfoa.fm_bw]))
953
        a_band.append(rs)
954

    
955
        rs = RadioSetting("upper.vfoa.cmp_nder", "Compandor",
956
                            RadioSettingValueBoolean(bool(_vfoa.cmp_nder)))
957
        a_band.append(rs)
958

    
959
        rs = RadioSetting("upper.vfoa.scrm_blr", "Scrambler",
960
                            RadioSettingValueBoolean(bool(_vfoa.scrm_blr)))
961
        a_band.append(rs)
962

    
963
        rs = RadioSetting("upper.vfoa.shift", "Xmit Shift",
964
                              RadioSettingValueList(LIST_SHIFT,LIST_SHIFT[_vfoa.shift]))
965
        a_band.append(rs)
966

    
967
        val  = _vfoa.offset / 100000.0
968
        rs = RadioSetting("upper.vfoa.offset", "Xmit Offset (MHz)",
969
                          RadioSettingValueFloat(0, 100.0,val, 0.001,3))
970
        rs.set_apply_callback(my_dbl2raw,_vfoa,"offset",0)                    # allow zero value
971
        a_band.append(rs)
972

    
973
        tmp = str(_vfoa.step/100.0)
974
        rs = RadioSetting("step", "Freq step (KHz)",
975
                              RadioSettingValueList(LIST_STEPS,tmp))
976
        rs.set_apply_callback(my_word2raw,_vfoa,"step",100)
977
        a_band.append(rs)
978

    
979
        if _vfoa.sql == 0xFF:
980
            val = 0x04
981
        else:
982
            val = _vfoa.sql
983

    
984
        rs = RadioSetting("upper.vfoa.sql", "Squelch",
985
                            RadioSettingValueInteger(0, 9, val))
986
        a_band.append(rs)
987

    
988
    # LOWER BAND SETTINGS    RJD
989

    
990
        val = _vfob.frq_chn_mode/2 
991
        rs = RadioSetting("lower.vfob.frq_chn_mode", "Default Mode",
992
                              RadioSettingValueList(LIST_VFOMODE, LIST_VFOMODE[val]))
993
        rs.set_apply_callback(my_spcl,_vfob,"frq_chn_mode") 
994
        b_band.append(rs)
995

    
996
        val = _vfob.chan_num + 1
997
        rs = RadioSetting("lower.vfob.chan_num", "Initial Chan", RadioSettingValueInteger(0, 127, val))
998
        rs.set_apply_callback(my_adjraw, _vfob,"chan_num",-1)  
999
        b_band.append(rs)
1000

    
1001
        val  = _vfob.rxfreq / 100000.0                   # RJD
1002
        rs = RadioSetting("lower.vfob.rxfreq ", "Default Recv Freq (MHz)",
1003
                          RadioSettingValueFloat(400.0, 480.0,val, 0.001,5))
1004
        rs.set_apply_callback(my_dbl2raw, _vfob,"rxfreq")
1005
        b_band.append(rs)
1006

    
1007
        tmp = my_tone_strn(_vfob, "is_rxdigtone", "rxdtcs_pol", "rx_tone")
1008
        rs = RadioSetting("rx_tone", "Default Recv CTCSS (Htz)",
1009
                              RadioSettingValueList(LIST_CTCSS,tmp))
1010
        rs.set_apply_callback(my_set_tone,_vfob,"is_rxdigtone", "rxdtcs_pol", "rx_tone")
1011
        b_band.append(rs)
1012

    
1013
        rs = RadioSetting("lower.vfob.rx_mode", "Default Recv Mode",
1014
                              RadioSettingValueList(LIST_RECVMODE,LIST_RECVMODE[_vfob.rx_mode]))
1015
        b_band.append(rs)
1016

    
1017
        tmp = my_tone_strn(_vfob, "is_txdigtone", "txdtcs_pol", "tx_tone")
1018
        rs = RadioSetting("tx_tone", "Default Xmit CTCSS (Htz)",
1019
                              RadioSettingValueList(LIST_CTCSS,tmp))
1020
        rs.set_apply_callback(my_set_tone,_vfob,"is_txdigtone", "txdtcs_pol", "tx_tone")
1021
        b_band.append(rs)
1022

    
1023
        rs = RadioSetting("lower.vfob.launch_sig", "Launch Signaling",
1024
                              RadioSettingValueList(LIST_SIGNAL,LIST_SIGNAL[_vfob.launch_sig]))
1025
        b_band.append(rs)
1026

    
1027
        rs = RadioSetting("lower.vfob.tx_end_sig", "Xmit End Signaling",
1028
                              RadioSettingValueList(LIST_SIGNAL,LIST_SIGNAL[_vfob.tx_end_sig]))
1029
        b_band.append(rs)
1030

    
1031
        val =  _vfob.power/2
1032
        rs = RadioSetting("lower.vfob.power", "Bank Power",
1033
                              RadioSettingValueList(LIST_POWER, LIST_POWER[val]))
1034
        b_band.append(rs)
1035

    
1036
        rs = RadioSetting("lower.vfob.fm_bw", "Wide/Narrow Band",
1037
                              RadioSettingValueList(LIST_BW,LIST_BW[_vfob.fm_bw]))
1038
        b_band.append(rs)
1039

    
1040
        rs = RadioSetting("lower.vfob.cmp_nder", "Compandor",
1041
                            RadioSettingValueBoolean(bool(_vfob.cmp_nder)))
1042
        b_band.append(rs)
1043

    
1044
        rs = RadioSetting("lower.vfob.scrm_blr", "Scrambler",
1045
                            RadioSettingValueBoolean(bool(_vfob.scrm_blr)))
1046
        b_band.append(rs)
1047

    
1048
        rs = RadioSetting("lower.vfob.shift", "Xmit Shift",
1049
                              RadioSettingValueList(LIST_SHIFT,LIST_SHIFT[_vfob.shift]))
1050
        b_band.append(rs)
1051

    
1052
        val  = _vfob.offset / 100000.0
1053
        rs = RadioSetting("lower.vfob.offset", "Xmit Offset (MHz)",
1054
                          RadioSettingValueFloat(0, 100.0,val, 0.001,3))
1055
        rs.set_apply_callback(my_dbl2raw, _vfob,"offset",0)
1056
        b_band.append(rs)
1057

    
1058
        tmp = str(_vfob.step/100.0)
1059
        rs = RadioSetting("step", "Freq step (KHz)",    
1060
                              RadioSettingValueList(LIST_STEPS,tmp))
1061
        rs.set_apply_callback(my_word2raw, _vfob,"step",100)
1062
        b_band.append(rs)
1063

    
1064
        if _vfob.sql == 0xFF:
1065
            val = 0x04
1066
        else:
1067
            val = _vfob.sql
1068

    
1069
        rs = RadioSetting("lower.vfob.sql", "Squelch",
1070
                            RadioSettingValueInteger(0, 9, val))
1071
        b_band.append(rs)
1072

    
1073
  # PowerOn & Freq Limits Settings
1074
 
1075
        def chars2str(cary, knt):                 # Convert raw memory char array to a string NOT a callback
1076
            stx = ""
1077
            for char in cary[:knt]:
1078
                stx += chr(char)
1079
            return stx
1080
  
1081
        def my_str2ary(setting, obj, atrba, atrbc):         #  < Callback: convert 7-char string to char array with count
1082
            ary = ""
1083
            knt = 7
1084
            for j in range (6, -1, -1):                # strip trailing whitespaces
1085
                if str(setting.value)[j]== "" or str(setting.value)[j]== " ":
1086
                    knt = knt -1
1087
                else: break
1088
    #       LOG.warning("Knt= "+str(knt))
1089
            for j in range(0, 7,1):
1090
                    if j < knt: ary += str(setting.value)[j]     # 'C','2','6','4'...
1091
                    else: ary += chr(0xFF)
1092
    #        LOG.warning("String="+ary)
1093
            setattr(obj,atrba,ary)
1094
            setattr(obj,atrbc,knt)
1095
            return
1096

    
1097
        tmp = chars2str(_lims.hello1, _lims.hello1_cnt)                
1098
        rs = RadioSetting("hello_lims.hello1", "Power-On Message 1",
1099
                            RadioSettingValueString(0, 7, tmp))
1100
        rs.set_apply_callback(my_str2ary,_lims,"hello1","hello1_cnt")
1101
        lims.append(rs)
1102
        
1103
        tmp = chars2str( _lims.hello2,_lims.hello2_cnt)
1104
        rs = RadioSetting("hello_lims.hello2", "Power-On Message 2",
1105
                            RadioSettingValueString(0, 7, tmp))
1106
        rs.set_apply_callback(my_str2ary,_lims,"hello2","hello2_cnt")
1107
        lims.append(rs)
1108

    
1109
#     VALID_BANDS = [(136000000, 176000000),400000000, 480000000)]
1110

    
1111
        lval  = _lims.vhf_low / 100000.0
1112
        uval  = _lims.vhf_high / 100000.0
1113
        if lval >= uval :
1114
            lval = 144.0
1115
            uval = 158.0
1116

    
1117
        rs = RadioSetting("hello_lims.vhf_low", "Lower VHF Band Limit (MHz)",
1118
                          RadioSettingValueFloat(136.0, 176.0,lval, 0.001,3))
1119
        rs.set_apply_callback(my_dbl2raw, _lims,"vhf_low")
1120
        lims.append(rs)
1121

    
1122
        rs = RadioSetting("hello_lims.vhf_high", "Upper VHF Band Limit (MHz)",
1123
                          RadioSettingValueFloat(136.0, 176.0,uval, 0.001,3))
1124
        rs.set_apply_callback(my_dbl2raw, _lims,"vhf_high")
1125
        lims.append(rs)
1126

    
1127
        lval  = _lims.uhf_low / 100000.0
1128
        uval  = _lims.uhf_high / 100000.0
1129
        if lval >= uval :
1130
            lval = 420.0
1131
            uval = 470.0
1132

    
1133
        rs = RadioSetting("hello_lims.uhf_low", "Lower UHF Band Limit (MHz)",
1134
                          RadioSettingValueFloat(400.0, 480.0,lval, 0.001,3))
1135
        rs.set_apply_callback(my_dbl2raw, _lims,"uhf_low")
1136
        lims.append(rs)
1137

    
1138
        rs = RadioSetting("hello_lims.uhf_high", "Upper UHF Band Limit (MHz)",
1139
                          RadioSettingValueFloat(400.0, 480.0,uval, 0.001,3))
1140
        rs.set_apply_callback(my_dbl2raw, _lims,"uhf_high")
1141
        lims.append(rs)
1142

    
1143
  # Codes and DTMF Groups Settings
1144
  
1145
        def make_dtmf(ary, knt):          # generate the DTMF code 1-8, NOT a callback
1146
            tmp = ""
1147
            if knt> 0:
1148
                for  val in ary[:knt]:
1149
                    if val >0 and val <=9: tmp +=  chr(val+48)
1150
                    elif val == 0x0a: tmp += "0"
1151
                    elif val == 0x0d: tmp += "A"
1152
                    elif val == 0x0e: tmp += "B"
1153
                    elif val == 0x0f: tmp += "C"
1154
                    elif val == 0x00: tmp += "D"
1155
                    elif val == 0x0b: tmp += "*"
1156
                    elif val == 0x0c: tmp += "#"
1157
                    else:
1158
                        msg = ("Invalid Character. Must be: 0-9,A,B,C,D,*,#")
1159
                        raise InvalidValueError(msg)
1160

    
1161
  #          LOG.warning("Tmp: "+tmp)
1162
            return tmp
1163

    
1164
        def my_dtmf2raw(setting, obj, atrba, atrbc, syz=7):   # <Callback: DTMF Code; sends 5 or 7-byte string
1165
            draw = []
1166
            knt = syz
1167
            for j in range (syz-1, -1, -1):                # strip trailing whitespaces
1168
                if str(setting.value)[j]== "" or str(setting.value)[j]== " ":
1169
                    knt = knt -1
1170
                else: break
1171
            for j in range(0, syz):
1172
                bx = str(setting.value)[j]                # 'C','2','6','4'...
1173
                obx = ord(bx)
1174
                dig = 0x0ff
1175
                if j < knt and knt > 0:                    # (Else) is pads
1176
                    if  bx == "0": dig = 0x0a
1177
                    elif  bx == "A": dig = 0x0d
1178
                    elif  bx == "B": dig = 0x0e
1179
                    elif  bx == "C": dig = 0x0f
1180
                    elif  bx == "D": dig = 0x00
1181
                    elif  bx == "*": dig = 0x0b
1182
                    elif  bx == "#": dig = 0x0c
1183
                    elif obx>=49 and obx<=57: dig = obx-48
1184
                    else:
1185
    #                    LOG.warning("Setting: "+str(setting)+", knt= "+str(knt)+", bx["+str(j)+"]= "+bx+", sofar= "+hex(draw))
1186
                        msg = ("Must be: 0-9,A,B,C,D,*,#")
1187
                        raise InvalidValueError(msg)
1188
                    # - end if/elif/else for bx
1189
                # - end if J<=knt
1190
                draw.append(dig)         # generate string of bytes
1191
            # - end for j
1192
     #       LOG.warning("DTMF raw= "+str(draw)+", Knt= "+str(knt))
1193
            setattr(obj, atrba, draw)
1194
            setattr(obj, atrbc, knt)
1195
            return 
1196

    
1197
        tmp = make_dtmf(_codes.native_id_code,_codes.native_id_cnt)
1198
        rs = RadioSetting("codes.native_id_code", "Native ID Code", RadioSettingValueString(0, 7, tmp))
1199
        rs.set_apply_callback(my_dtmf2raw, _codes,"native_id_code","native_id_cnt",7)
1200
        codes.append(rs)
1201

    
1202
        tmp = make_dtmf( _codes.master_id_code,_codes.master_id_cnt)
1203
        rs = RadioSetting("codes.master_id_code", "Master Control ID Code", RadioSettingValueString(0, 7, tmp))
1204
        rs.set_apply_callback(my_dtmf2raw, _codes,"master_id_code","master_id_cnt",7)
1205
        codes.append(rs)
1206

    
1207
        tmp = make_dtmf(  _codes.alarm_code,_codes.alarm_cnt)
1208
        rs = RadioSetting("codes.alarm_code", "Alarm Code", RadioSettingValueString(0, 5, tmp))
1209
        rs.set_apply_callback(my_dtmf2raw, _codes,"alarm_code","alarm_cnt",5)
1210
        codes.append(rs)
1211

    
1212
        tmp = make_dtmf(  _codes.id_disp_code,_codes.id_disp_cnt)
1213
        rs = RadioSetting("codes.id_disp_code", "Identify Display Code", RadioSettingValueString(0, 5, tmp))
1214
        rs.set_apply_callback(my_dtmf2raw, _codes,"id_disp_code","id_disp_cnt",5)
1215
        codes.append(rs)
1216

    
1217
        tmp = make_dtmf(  _codes.revive_code,_codes.revive_cnt)
1218
        rs = RadioSetting("codes.revive_code", "Revive Code", RadioSettingValueString(0, 5, tmp))
1219
        rs.set_apply_callback(my_dtmf2raw,_codes,"revive_code","revive_cnt",5)
1220
        codes.append(rs)
1221

    
1222
        tmp = make_dtmf(  _codes.stun_code,_codes.stun_cnt)
1223
        rs = RadioSetting("codes.stun_code", "Remote Stun Code", RadioSettingValueString(0, 5, tmp))
1224
        rs.set_apply_callback(my_dtmf2raw, _codes,"stun_code","stun_cnt",5)
1225
        codes.append(rs)
1226

    
1227
        tmp = make_dtmf( _codes.kill_code,_codes.kill_cnt)
1228
        rs = RadioSetting("codes.kill_code", "Remote KILL Code", RadioSettingValueString(0, 5, tmp))
1229
        rs.set_apply_callback(my_dtmf2raw, _codes,"kill_code","kill_cnt",5)
1230
        codes.append(rs)
1231

    
1232
        tmp = make_dtmf( _codes.monitor_code,_codes.monitor_cnt)
1233
        rs = RadioSetting("codes.monitor_code", "Monitor Code", RadioSettingValueString(0, 5, tmp))
1234
        rs.set_apply_callback(my_dtmf2raw, _codes, "monitor_code", "monitor_cnt",5)
1235
        codes.append(rs)
1236

    
1237
        val = _codes.state_now
1238
        if val > 2 :
1239
            val = 0
1240

    
1241
        rs = RadioSetting("codes.state_now", "Current State",
1242
                              RadioSettingValueList(LIST_STATE,LIST_STATE[val]))
1243
        codes.append(rs)
1244

    
1245
        dtm = make_dtmf(_dtmf.dtmf1, _dtmf.dtmf1_cnt)
1246
#        LOG.warning("DTMF: "+dtm)
1247
        rs = RadioSetting("dtmf_tab.dtmf1", "DTMF1 String", RadioSettingValueString(0, 7, dtm))
1248
        rs.set_apply_callback(my_dtmf2raw,_dtmf,"dtmf1","dtmf1_cnt")
1249
        codes.append(rs)
1250

    
1251
        dtm = make_dtmf(_dtmf.dtmf2, _dtmf.dtmf2_cnt)
1252
        rs = RadioSetting("dtmf_tab.dtmf2", "DTMF2 String", RadioSettingValueString(0, 7, dtm))
1253
        rs.set_apply_callback(my_dtmf2raw,_dtmf,"dtmf2","dtmf2_cnt")
1254
        codes.append(rs)
1255

    
1256
        dtm = make_dtmf(_dtmf.dtmf3, _dtmf.dtmf3_cnt)
1257
        rs = RadioSetting("dtmf_tab.dtmf3", "DTMF3 String", RadioSettingValueString(0, 7, dtm))
1258
        rs.set_apply_callback(my_dtmf2raw,_dtmf,"dtmf3","dtmf3_cnt")
1259
        codes.append(rs)
1260

    
1261
        dtm = make_dtmf(_dtmf.dtmf4, _dtmf.dtmf4_cnt)
1262
        rs = RadioSetting("dtmf_tab.dtmf4", "DTMF4 String", RadioSettingValueString(0, 7, dtm))
1263
        rs.set_apply_callback(my_dtmf2raw,_dtmf,"dtmf4","dtmf4_cnt")
1264
        codes.append(rs)
1265

    
1266
        dtm = make_dtmf(_dtmf.dtmf5, _dtmf.dtmf5_cnt)
1267
        rs = RadioSetting("dtmf_tab.dtmf5", "DTMF5 String", RadioSettingValueString(0, 7, dtm))
1268
        rs.set_apply_callback(my_dtmf2raw,_dtmf,"dtmf5","dtmf5_cnt")
1269
        codes.append(rs)
1270

    
1271
        dtm = make_dtmf(_dtmf.dtmf6, _dtmf.dtmf6_cnt)
1272
        rs = RadioSetting("dtmf_tab.dtmf6", "DTMF6 String", RadioSettingValueString(0, 7, dtm))
1273
        rs.set_apply_callback(my_dtmf2raw,_dtmf,"dtmf6","dtmf6_cnt")
1274
        codes.append(rs)
1275

    
1276
        dtm = make_dtmf(_dtmf.dtmf7, _dtmf.dtmf7_cnt)
1277
        rs = RadioSetting("dtmf_tab.dtmf7", "DTMF7 String", RadioSettingValueString(0, 7, dtm))
1278
        rs.set_apply_callback(my_dtmf2raw,_dtmf,"dtmf7","dtmf7_cnt")
1279
        codes.append(rs)
1280

    
1281
        dtm = make_dtmf(_dtmf.dtmf8, _dtmf.dtmf8_cnt)
1282
        rs = RadioSetting("dtmf_tab.dtmf8", "DTMF8 String", RadioSettingValueString(0, 7, dtm))
1283
        rs.set_apply_callback(my_dtmf2raw,_dtmf,"dtmf8","dtmf8_cnt")
1284
        codes.append(rs)
1285

    
1286
        return group       # END get_settings()
1287
   
1288

    
1289
    def set_settings(self, settings): 
1290
        _settings = self._memobj.settings
1291
        _mem = self._memobj
1292
        for element in settings:
1293
            if not isinstance(element, RadioSetting):
1294
                self.set_settings(element)
1295
                continue
1296
            else:
1297
                try:
1298
                    name = element.get_name()
1299
                    if "." in name:
1300
                        bits = name.split(".")
1301
                        obj = self._memobj
1302
                        for bit in bits[:-1]:
1303
                            if "/" in bit:
1304
                                bit, index = bit.split("/", 1)
1305
                                index = int(index)
1306
                                obj = getattr(obj, bit)[index]
1307
                            else:
1308
                                obj = getattr(obj, bit)
1309
                        setting = bits[-1]
1310
                    else:
1311
                        obj = _settings
1312
                        setting = element.get_name()
1313

    
1314
                    if element.has_apply_callback():
1315
                        LOG.debug("Using apply callback")
1316
                        element.run_apply_callback()
1317
                    elif element.value.get_mutable():
1318
                        LOG.debug("Setting %s = %s" % (setting, element.value))
1319
                        setattr(obj, setting, element.value)
1320
                except Exception, e:
1321
                    LOG.debug(element.get_name())
1322
                    raise
1323

    
1324

    
1325
    @classmethod
1326
    def match_model(cls, filedata, filename):
1327
        match_size = False
1328
        match_model = False
1329

    
1330
        # testing the file data size
1331
  #      if len(filedata) == MEM_SIZE + 8:         " LT-725UV
1332
        if len(filedata) == MEM_SIZE + 6:                             # BJ-218   RJD
1333
             match_size = True
1334

    
1335
        # testing the firmware model fingerprint
1336
        match_model = model_match(cls, filedata)
1337

    
1338
        if match_size and match_model:
1339
            return True
1340
        else:
1341
            return False
1342

    
1343

    
1344
class BJ218Upper(BJ218):
1345
    VARIANT = "Upper"
1346
    _vfo = "upper"
1347

    
1348

    
1349
class BJ218Lower(BJ218):
1350
    VARIANT = "Lower"
1351
    _vfo = "lower"