Project

General

Profile

New Model #10865 » baofeng_uv17.py

Should work with newest version of chirp - Sander van der Wel, 11/21/2023 01:42 PM

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

    
19
import logging
20

    
21
from chirp import chirp_common, directory, memmap
22
from chirp import bitwise
23
from chirp.settings import RadioSettingGroup, RadioSetting, \
24
    RadioSettingValueBoolean, RadioSettingValueList, \
25
    RadioSettingValueString, RadioSettingValueInteger, \
26
    RadioSettingValueFloat, RadioSettings, \
27
    InvalidValueError
28
import time
29
import struct
30
import logging
31
from chirp.drivers import baofeng_common
32
from chirp import errors, util
33

    
34
LOG = logging.getLogger(__name__)
35

    
36
DTMF_CHARS = "0123456789 *#ABCD"
37
STEPS = [2.5, 5.0, 6.25, 10.0, 12.5, 20.0, 25.0, 50.0]
38

    
39
LIST_AB = ["A", "B"]
40
LIST_ALMOD = ["Site", "Tone", "Code"]
41
LIST_BANDWIDTH = ["Wide", "Narrow"]
42
LIST_COLOR = ["Off", "Blue", "Orange", "Purple"]
43
LIST_DTMFSPEED = ["%s ms" % x for x in range(50, 2010, 10)]
44
LIST_DTMFST = ["Off", "DT-ST", "ANI-ST", "DT+ANI"]
45
LIST_MODE = ["Channel", "Name", "Frequency"]
46
LIST_OFF1TO9 = ["Off"] + list("123456789")
47
LIST_OFF1TO10 = LIST_OFF1TO9 + ["10"]
48
LIST_OFFAB = ["Off"] + LIST_AB
49
LIST_RESUME = ["TO", "CO", "SE"]
50
LIST_PONMSG = ["Full", "Message"]
51
LIST_PTTID = ["Off", "BOT", "EOT", "Both"]
52
LIST_SCODE = ["%s" % x for x in range(1, 16)]
53
LIST_RPSTE = ["Off"] + ["%s" % x for x in range(1, 11)]
54
LIST_SAVE = ["Off", "1:1", "1:2", "1:3", "1:4"]
55
LIST_SHIFTD = ["Off", "+", "-"]
56
LIST_STEDELAY = ["Off"] + ["%s ms" % x for x in range(100, 1100, 100)]
57
LIST_STEP = [str(x) for x in STEPS]
58
LIST_TIMEOUT = ["Off"] + ["%s sec" % x for x in range(15, 615, 15)]
59
LIST_TXPOWER = ["High", "Mid", "Low"]
60
LIST_VOICE = ["Chinese", "English"]
61
LIST_WORKMODE = ["Frequency", "Channel"]
62

    
63
TXP_CHOICES = ["High", "Low"]
64
TXP_VALUES = [0x00, 0x02]
65

    
66
def model_match(cls, data):
67
    """Match the opened/downloaded image to the correct version"""
68

    
69
    if data[0:2] == b"\x0A\x0D":
70
        return True
71
    else:
72
        return False
73
    
74
STIMEOUT = 1.5
75

    
76
def _clean_buffer(radio):
77
    radio.pipe.timeout = 0.005
78
    junk = radio.pipe.read(256)
79
    radio.pipe.timeout = STIMEOUT
80
    if junk:
81
        LOG.debug("Got %i bytes of junk before starting" % len(junk))
82

    
83

    
84
def _rawrecv(radio, amount):
85
    """Raw read from the radio device"""
86
    data = ""
87
    try:
88
        data = radio.pipe.read(amount)
89
    except:
90
        msg = "Generic error reading data from radio; check your cable."
91
        raise errors.RadioError(msg)
92

    
93
    if len(data) != amount:
94
        msg = "Error reading data from radio: not the amount of data we want."
95
        raise errors.RadioError(msg)
96

    
97
    return data
98

    
99

    
100
def _rawsend(radio, data):
101
    """Raw send to the radio device"""
102
    try:
103
        #print(data)
104
        #print(radio)
105
        radio.pipe.write(data)
106
    except:
107
        raise errors.RadioError("Error sending data to radio")
108

    
109
def _make_read_frame(addr, length):
110
    """Pack the info in the header format"""
111
    frame = _make_frame(b'\x52', addr, length)
112
    # Return the data
113
    return frame
114

    
115
def _make_frame(cmd, addr, length, data=""):
116
    """Pack the info in the header format"""
117
    frame = cmd + struct.pack("i",addr)[:-1]+struct.pack("b", length)
118
    # add the data if set
119
    if len(data) != 0:
120
        frame += data
121
    # return the data
122
    return frame
123

    
124

    
125
def _recv(radio, addr, length):
126
    """Get data from the radio """
127
    # read 4 bytes of header
128
    hdr = _rawrecv(radio, 4)
129

    
130
    # read data
131
    data = _rawrecv(radio, length)
132

    
133
    # DEBUG
134
    LOG.info("Response:")
135
    LOG.debug(util.hexprint(hdr + data))
136

    
137
    c, a, l = struct.unpack(">BHB", hdr)
138
    if a != addr or l != length or c != ord("X"):
139
        LOG.error("Invalid answer for block 0x%04x:" % addr)
140
        LOG.debug("CMD: %s  ADDR: %04x  SIZE: %02x" % (c, a, l))
141
        raise errors.RadioError("Unknown response from the radio")
142

    
143
    return data
144

    
145
def _sendmagic(radio, magic, response):
146
    _rawsend(radio, magic)
147
    ack = _rawrecv(radio, len(response))
148
    if ack != response:
149
        if ack:
150
            LOG.debug(repr(ack))
151
        raise errors.RadioError("Radio did not respond to enter read mode")
152
    
153
def _do_ident(radio):
154
    """Put the radio in PROGRAM mode & identify it"""
155
    radio.pipe.baudrate = radio.BAUDRATE
156
    radio.pipe.parity = "N"
157
    radio.pipe.timeout = STIMEOUT
158

    
159
    # Flush input buffer
160
    _clean_buffer(radio)
161

    
162
    # Ident radio
163
    magic = radio._magic0
164
    _rawsend(radio, magic)
165
    ack = _rawrecv(radio, 8)
166

    
167
    if not ack.startswith(radio._fingerprint):
168
        if ack:
169
            LOG.debug(repr(ack))
170
        raise errors.RadioError("Radio did not respond as expected (A)")
171

    
172
    return True
173

    
174
def _getMemoryMap(radio):
175
    # Get memory map
176
    memory_map = []
177
    for addr in range(0x1FFF, 0x10FFF, 0x1000):
178
        frame = _make_frame(b"R", addr, 1)
179
        _rawsend(radio, frame)
180
        blocknr = ord(_rawrecv(radio, 6)[5:])
181
        blocknr = (blocknr>>4&0xf)*10 + (blocknr&0xf)
182
        memory_map += [blocknr]
183
        _sendmagic(radio, b"\x06", b"\x06")
184
    return memory_map
185

    
186
def _download(radio):
187
    """Get the memory map"""
188

    
189
    # Put radio in program mode and identify it
190
    _do_ident(radio)
191
    
192
    data = b""
193
    # Enter read mode
194
    _sendmagic(radio, radio._magic2, b"\x50\x00\x00")
195
    _sendmagic(radio, radio._magic3, b"\x06")
196

    
197
    # Start data with some unknown stuff to be compatible with the official CPS app
198
    _rawsend(radio, b"\x56\x00\x00\x0A\x0D")
199
    d = _rawrecv(radio, 13)
200
    data += d[3:] + 6 * b"\x00"
201
    _sendmagic(radio, b"\x06", b"\x06")
202
    _rawsend(radio, b"\x56\x00\x10\x0A\x0D")
203
    d = _rawrecv(radio, 13)
204
    data += d[3:] + 6 * b"\x00"
205
    _sendmagic(radio, b"\x06", b"\x06")
206
    _rawsend(radio, b"\x56\x00\x20\x0A\x0D")
207
    d = _rawrecv(radio, 13)
208
    data += d[3:] + 6 * b"\x00"
209
    _sendmagic(radio, b"\x06", b"\x06")
210
    data += (0x2000 - 0x30) * b"\x00"
211

    
212
    _sendmagic(radio, b"\x56\x00\x00\x00\x0A", b"\x56\x0A\x08\x00\x10\x00\x00\xFF\xFF\x00\x00")
213
    _sendmagic(radio, b"\x06", b"\x06")
214
    _sendmagic(radio, radio._magic4, b"\x06")
215
    _sendmagic(radio, b"\02", b"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF")
216
    _sendmagic(radio, b"\x06", b"\x06")
217

    
218
    # Get memory map
219
    memory_map = _getMemoryMap(radio)
220

    
221
    # UI progress
222
    status = chirp_common.Status()
223
    status.cur = 0
224
    status.max = radio.MEM_TOTAL // radio.BLOCK_SIZE
225
    status.msg = "Cloning from radio..."
226
    radio.status_fn(status)
227

    
228
    for block_number in radio.BLOCK_ORDER:
229
        block_index = memory_map.index(block_number) + 1
230
        start_addr = block_index * 0x1000
231
        for addr in range(start_addr, start_addr + 0x1000, radio.BLOCK_SIZE):
232
            frame = _make_read_frame(addr, radio.BLOCK_SIZE)
233
            # DEBUG
234
            LOG.debug("Frame=" + util.hexprint(frame))
235

    
236
            # Sending the read request
237
            _rawsend(radio, frame)
238

    
239
            # Now we read data
240
            d = _rawrecv(radio, radio.BLOCK_SIZE + 5)
241

    
242
            LOG.debug("Response Data= " + util.hexprint(d))
243

    
244
            # Aggregate the data
245
            data += d[5:]
246

    
247
            # UI Update
248
            status.cur = len(data) // radio.BLOCK_SIZE
249
            status.msg = "Cloning from radio..."
250
            radio.status_fn(status)
251

    
252
            # ACK ACK
253
            _sendmagic(radio, b"\x06", b"\x06")
254

    
255
    return data
256

    
257
def _upload(radio):
258
    """Upload procedure"""
259
    # Put radio in program mode and identify it
260
    _do_ident(radio)
261
    
262
    # Enter read mode
263
    _sendmagic(radio, radio._magic2, b"\x50\x00\x00")
264
    _sendmagic(radio, radio._magic3, b"\x06")
265

    
266
    # Start data with some unknown stuff to be compatible with the official CPS app
267
    _rawsend(radio, b"\x56\x00\x00\x0A\x0D")
268
    d = _rawrecv(radio, 13)
269
    _sendmagic(radio, b"\x06", b"\x06")
270
    _rawsend(radio, b"\x56\x00\x10\x0A\x0D")
271
    d = _rawrecv(radio, 13)
272
    _sendmagic(radio, b"\x06", b"\x06")
273
    _rawsend(radio, b"\x56\x00\x20\x0A\x0D")
274
    d = _rawrecv(radio, 13)
275
    _sendmagic(radio, b"\x06", b"\x06")
276

    
277
    _sendmagic(radio, b"\x56\x00\x00\x00\x0A", b"\x56\x0A\x08\x00\x10\x00\x00\xFF\xFF\x00\x00")
278
    _sendmagic(radio, b"\x06", b"\x06")
279
    _sendmagic(radio, radio._magic4, b"\x06")
280
    _sendmagic(radio, b"\02", b"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF")
281
    _sendmagic(radio, b"\x06", b"\x06")
282

    
283
    # Get memory map
284
    memory_map = _getMemoryMap(radio)
285
 
286
    # UI progress
287
    status = chirp_common.Status()
288
    status.cur = 0
289
    status.max = radio.WRITE_MEM_TOTAL // radio.BLOCK_SIZE
290
    status.msg = "Cloning to radio..."
291
    radio.status_fn(status)
292

    
293
    # the fun start here
294
    data_addr = 0x3000
295
    for block_number in radio.WRITE_BLOCK_ORDER:
296
        block_index = memory_map.index(block_number) + 1
297
        start_addr = block_index * 0x1000
298
        data_start_addr = radio.BLOCK_LOCATIONS[radio.BLOCK_ORDER.index(block_number)]
299
        for addr in range(start_addr, start_addr + 0x1000, radio.BLOCK_SIZE):
300
            # sending the data
301
            data_addr = data_start_addr + addr - start_addr
302
            data = radio.get_mmap()[data_addr:data_addr + radio.BLOCK_SIZE]
303

    
304
            frame = _make_frame(b"W", addr, radio.BLOCK_SIZE, data)
305
            #print()
306
            #print(hex(data_addr))
307
            #print(util.hexprint(frame))
308
            _rawsend(radio, frame)
309
            #time.sleep(0.05)
310

    
311
            # receiving the response
312
            ack = _rawrecv(radio, 1)
313
            #ack = b"\x06"
314
            if ack != b"\x06":
315
                msg = "Bad ack writing block 0x%04x" % addr
316
                raise errors.RadioError(msg)
317

    
318
            # UI Update
319
            status.cur = (data_addr - 0x3000) // radio.BLOCK_SIZE
320
            status.msg = "Cloning to radio..."
321
            radio.status_fn(status)
322

    
323

    
324
def _split(rf, f1, f2):
325
    """Returns False if the two freqs are in the same band (no split)
326
    or True otherwise"""
327

    
328
    # determine if the two freqs are in the same band
329
    for low, high in rf.valid_bands:
330
        if f1 >= low and f1 <= high and \
331
                f2 >= low and f2 <= high:
332
            # if the two freqs are on the same Band this is not a split
333
            return False
334

    
335
    # if you get here is because the freq pairs are split
336
    return True
337

    
338

    
339
@directory.register
340

    
341
class UV17(baofeng_common.BaofengCommonHT):
342
    """Baofeng UV-17"""
343
    VENDOR = "Baofeng"
344
    MODEL = "UV-17"
345
    NEEDS_COMPAT_SERIAL = False
346

    
347
    BLOCK_ORDER = [2, 16, 17, 18, 19,  24, 25, 26, 4, 6]
348
    BLOCK_LOCATIONS = [0x2000, 0x3000, 0x4000, 0x5000, 0x6000, 0x7000, 0x8000, 0x9000, 0xA000, 0xB000]
349
    WRITE_BLOCK_ORDER = [16, 17, 18, 19, 24, 25, 26, 4, 6]
350

    
351
    MEM_TOTAL = 0xC000
352
    WRITE_MEM_TOTAL = 0x9000
353
    BLOCK_SIZE = 0x40
354
    STIMEOUT = 2
355
    BAUDRATE = 57600
356

    
357
    _gmrs = False
358
    _bw_shift = False
359

    
360
    _magic0 = b"PSEARCH"
361
    _magic2 = b"PASSSTA"
362
    _magic3 = b"SYSINFO"
363
    _magic4 = b"\xFF\xFF\xFF\xFF\x0C\x55\x56\x31\x35\x39\x39\x39"
364
    _fingerprint = b"\x06" + b"UV15999"
365

    
366
    _tri_band = False
367

    
368
    MODES = ["NFM", "FM"]
369
    VALID_CHARS = chirp_common.CHARSET_ALPHANUMERIC + \
370
        "!@#$%^&*()+-=[]:\";'<>?,./"
371
    LENGTH_NAME = 11
372
    SKIP_VALUES = ["", "S"]
373
    DTCS_CODES = tuple(sorted(chirp_common.DTCS_CODES + (645,)))
374
    POWER_LEVELS = [chirp_common.PowerLevel("Low",  watts=1.00),
375
                    chirp_common.PowerLevel("High", watts=5.00)]
376
    _vhf_range = (130000000, 180000000)
377
    _vhf2_range = (200000000, 260000000)
378
    _uhf_range = (400000000, 521000000)
379
    VALID_BANDS = [_vhf_range,
380
                   _uhf_range]
381
    PTTID_LIST = LIST_PTTID
382
    SCODE_LIST = LIST_SCODE
383

    
384
    MEM_FORMAT = """
385
    #seekto 0x3030;
386
    struct {
387
      lbcd rxfreq[4];
388
      lbcd txfreq[4];
389
      u8 unused1:8;
390
      ul16 rxtone;
391
      ul16 txtone;
392
      u8 unknown1:1,
393
         bcl:1,
394
         pttid:2,
395
         unknown2:1,
396
         wide:1,
397
         lowpower:1,
398
         unknown:1;
399
      u8 scode:4,
400
         unknown3:3,
401
         scan:1;
402
      u8 unknown4:8;
403
    } memory[1002];
404

    
405
    #seekto 0xA040;
406
    struct {
407
      u8 timeout;
408
      u8 squelch;
409
      u8 vox;
410
      u8 unknown:6,
411
         voice: 1,
412
         voicealert: 1;
413
      u8 unknown1:8;
414
      u8 unknown2:8;
415
    } settings;
416

    
417
    struct vfo {
418
      lbcd rxfreq[4];
419
      lbcd txfreq[4];
420
      u8 unused1:8;
421
      ul16 rxtone;
422
      ul16 txtone;
423
      u8 unknown1:1,
424
         bcl:1,
425
         pttid:2,
426
         unknown2:1,
427
         wide:1,
428
         lowpower:1,
429
         unknown:1;
430
      u8 scode:4,
431
         unknown3:3,
432
         scan:1;
433
      u8 unknown4:8;
434
    };
435

    
436
    #seekto 0x3010;
437
    struct {
438
      struct vfo a;
439
      struct vfo b;
440
    } vfo;
441

    
442
    #seekto 0x7000;
443
    struct {
444
      char name[11];
445
    } names[999];
446
    """
447

    
448
    @classmethod
449
    def get_prompts(cls):
450
        rp = chirp_common.RadioPrompts()
451
        rp.experimental = \
452
            ('This driver is a beta version.\n'
453
             '\n'
454
             'Please save an unedited copy of your first successful\n'
455
             'download to a CHIRP Radio Images(*.img) file.'
456
             )
457
        rp.pre_download = _(
458
            "Follow these instructions to download your info:\n"
459
            "1 - Turn off your radio\n"
460
            "2 - Connect your interface cable\n"
461
            "3 - Turn on your radio\n"
462
            "4 - Do the download of your radio data\n")
463
        rp.pre_upload = _(
464
            "Follow this instructions to upload your info:\n"
465
            "1 - Turn off your radio\n"
466
            "2 - Connect your interface cable\n"
467
            "3 - Turn on your radio\n"
468
            "4 - Do the upload of your radio data\n")
469
        return rp
470

    
471
    def process_mmap(self):
472
        """Process the mem map into the mem object"""
473
        self._memobj = bitwise.parse(self.MEM_FORMAT, self._mmap)
474

    
475
    def get_settings(self):
476
        """Translate the bit in the mem_struct into settings in the UI"""
477
        _mem = self._memobj
478
        basic = RadioSettingGroup("basic", "Basic Settings")
479
        advanced = RadioSettingGroup("advanced", "Advanced Settings")
480
        other = RadioSettingGroup("other", "Other Settings")
481
        work = RadioSettingGroup("work", "Work Mode Settings")
482
        fm_preset = RadioSettingGroup("fm_preset", "FM Preset")
483
        dtmfe = RadioSettingGroup("dtmfe", "DTMF Encode Settings")
484
        service = RadioSettingGroup("service", "Service Settings")
485
        top = RadioSettings(basic, advanced, other, work, fm_preset, dtmfe,
486
                            service)
487
        print(_mem.settings)
488

    
489
        # Basic settings
490
        if _mem.settings.squelch > 0x09:
491
            val = 0x00
492
        else:
493
            val = _mem.settings.squelch
494
        rs = RadioSetting("settings.squelch", "Squelch",
495
                          RadioSettingValueList(
496
                              LIST_OFF1TO9, LIST_OFF1TO9[val]))
497
        basic.append(rs)
498

    
499
        if _mem.settings.timeout > 0x27:
500
            val = 0x03
501
        else:
502
            val = _mem.settings.timeout
503
        rs = RadioSetting("settings.timeout", "Timeout Timer",
504
                          RadioSettingValueList(
505
                              LIST_TIMEOUT, LIST_TIMEOUT[val]))
506
        basic.append(rs)
507

    
508
        if _mem.settings.voice > 0x02:
509
            val = 0x01
510
        else:
511
            val = _mem.settings.voice
512
        rs = RadioSetting("settings.voice", "Voice Prompt",
513
                          RadioSettingValueList(
514
                              LIST_VOICE, LIST_VOICE[val]))
515
        basic.append(rs)
516

    
517
        rs = RadioSetting("settings.voicealert", "Voice Alert",
518
                          RadioSettingValueBoolean(_mem.settings.voicealert))
519
        basic.append(rs)
520

    
521

    
522
        return top
523

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

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

    
555
    def get_features(self):
556
        """Get the radio's features"""
557

    
558
        rf = chirp_common.RadioFeatures()
559
        rf.has_settings = True
560
        rf.has_bank = False
561
        rf.has_tuning_step = False
562
        rf.can_odd_split = True
563
        rf.has_name = True
564
        rf.has_offset = True
565
        rf.has_mode = True
566
        rf.has_dtcs = True
567
        rf.has_rx_dtcs = True
568
        rf.has_dtcs_polarity = True
569
        rf.has_ctone = True
570
        rf.has_cross = True
571
        rf.valid_modes = self.MODES
572
        rf.valid_characters = self.VALID_CHARS
573
        rf.valid_name_length = self.LENGTH_NAME
574
        if self._gmrs:
575
            rf.valid_duplexes = ["", "+", "off"]
576
        else:
577
            rf.valid_duplexes = ["", "-", "+", "split", "off"]
578
        rf.valid_tmodes = ['', 'Tone', 'TSQL', 'DTCS', 'Cross']
579
        rf.valid_cross_modes = [
580
            "Tone->Tone",
581
            "DTCS->",
582
            "->DTCS",
583
            "Tone->DTCS",
584
            "DTCS->Tone",
585
            "->Tone",
586
            "DTCS->DTCS"]
587
        rf.valid_skips = self.SKIP_VALUES
588
        rf.valid_dtcs_codes = self.DTCS_CODES
589
        rf.memory_bounds = (0, 998)
590
        rf.valid_power_levels = self.POWER_LEVELS
591
        rf.valid_bands = self.VALID_BANDS
592
        rf.valid_tuning_steps = STEPS
593

    
594
        return rf
595
 
596
    def get_memory(self, number):
597
        offset = 0
598
        #skip 16 bytes at memory block boundary
599
        if number >= 252:
600
            offset += 1
601
        if number >= 507:
602
            offset += 1
603
        if number >= 762:
604
            offset += 1
605

    
606
        _mem = self._memobj.memory[number + offset]
607
        _nam = self._memobj.names[number]
608

    
609
        mem = chirp_common.Memory()
610
        mem.number = number
611

    
612
        if _mem.get_raw()[0] == 255:
613
            mem.empty = True
614
            return mem
615

    
616
        mem.freq = int(_mem.rxfreq) * 10
617

    
618
        if self._is_txinh(_mem):
619
            # TX freq not set
620
            mem.duplex = "off"
621
            mem.offset = 0
622
        else:
623
            # TX freq set
624
            offset = (int(_mem.txfreq) * 10) - mem.freq
625
            if offset != 0:
626
                if _split(self.get_features(), mem.freq, int(
627
                          _mem.txfreq) * 10):
628
                    mem.duplex = "split"
629
                    mem.offset = int(_mem.txfreq) * 10
630
                elif offset < 0:
631
                    mem.offset = abs(offset)
632
                    mem.duplex = "-"
633
                elif offset > 0:
634
                    mem.offset = offset
635
                    mem.duplex = "+"
636
            else:
637
                mem.offset = 0
638

    
639
        for char in _nam.name:
640
            if (str(char) == "\xFF") | (str(char) == "\x00"):
641
                char = " "  # The OEM software may have 0xFF mid-name
642
            mem.name += str(char)
643
        mem.name = mem.name.rstrip()
644

    
645
        dtcs_pol = ["N", "N"]
646
        txtone = int(_mem.txtone)
647
        rxtone = int(_mem.rxtone)
648
        if _mem.txtone in [0, 0xFFFF]:
649
            txmode = ""
650
        elif (_mem.txtone & 0x8000) > 0:
651
            txmode = "DTCS"
652
            mem.dtcs = (_mem.txtone&0x0f) + (_mem.txtone>>4&0xf)*10 + (_mem.txtone>>8&0xf)*100
653
            if (_mem.txtone & 0xC000) == 0xC000:
654
                dtcs_pol[0] = "R"
655
        else:
656
            txmode = "Tone"
657
            mem.rtone = int((_mem.txtone&0x0f) + (_mem.txtone>>4&0xf)*10 + (_mem.txtone>>8&0xf)*100 + (_mem.txtone>>12&0xf)*1000) / 10.0
658

    
659
        if _mem.rxtone in [0, 0xFFFF]:
660
            rxmode = ""
661
        elif (_mem.rxtone & 0x8000) > 0:
662
            rxmode = "DTCS"
663
            mem.rx_dtcs = (_mem.rxtone&0x0f) + (_mem.rxtone>>4&0xf)*10 + (_mem.rxtone>>8&0xf)*100
664
            if (_mem.rxtone & 0xC000) == 0xC000:
665
                dtcs_pol[1] = "R"
666
        else:
667
            rxmode = "Tone"
668
            mem.ctone = int((_mem.rxtone&0x0f) + (_mem.rxtone>>4&0xf)*10 + (_mem.rxtone>>8&0xf)*100 + (_mem.txtone>>12&0xf)*1000) / 10.0
669

    
670
        if txmode == "Tone" and not rxmode:
671
            mem.tmode = "Tone"
672
        elif txmode == rxmode and txmode == "Tone" and mem.rtone == mem.ctone:
673
            mem.tmode = "TSQL"
674
        elif txmode == rxmode and txmode == "DTCS" and mem.dtcs == mem.rx_dtcs:
675
            mem.tmode = "DTCS"
676
        elif rxmode or txmode:
677
            mem.tmode = "Cross"
678
            mem.cross_mode = "%s->%s" % (txmode, rxmode)
679

    
680
        mem.dtcs_polarity = "".join(dtcs_pol)
681

    
682
        if not _mem.scan:
683
            mem.skip = "S"
684

    
685
        levels = self.POWER_LEVELS
686
        try:
687
            mem.power = levels[_mem.lowpower]
688
        except IndexError:
689
            LOG.error("Radio reported invalid power level %s (in %s)" %
690
                        (_mem.power, levels))
691
            mem.power = levels[0]
692

    
693
        mem.mode = _mem.wide and "FM" or "NFM"
694

    
695
        mem.extra = RadioSettingGroup("Extra", "extra")
696

    
697
        rs = RadioSetting("bcl", "BCL",
698
                          RadioSettingValueBoolean(_mem.bcl))
699
        mem.extra.append(rs)
700

    
701
        rs = RadioSetting("pttid", "PTT ID",
702
                          RadioSettingValueList(self.PTTID_LIST,
703
                                                self.PTTID_LIST[_mem.pttid]))
704
        mem.extra.append(rs)
705

    
706
        rs = RadioSetting("scode", "S-CODE",
707
                          RadioSettingValueList(self.SCODE_LIST,
708
                                                self.SCODE_LIST[_mem.scode - 1]))
709
        mem.extra.append(rs)
710

    
711
        return mem
712

    
713
    def set_memory(self, mem):
714
        offset = 0
715
        #skip 16 bytes at memory block boundary
716
        if mem.number >= 252:
717
            offset += 1
718
        if mem.number >= 507:
719
            offset += 1
720
        if mem.number >= 762:
721
            offset += 1
722
        _mem = self._memobj.memory[mem.number + offset]
723
        _nam = self._memobj.names[mem.number]
724

    
725
        if mem.empty:
726
            _mem.set_raw("\xff" * 16)
727
            _nam.set_raw("\xff" * 16)
728
            return
729

    
730
        _mem.set_raw("\x00" * 16)
731
        _mem.rxfreq = mem.freq / 10
732
        
733
        if mem.duplex == "off":
734
            for i in range(0, 4):
735
                _mem.txfreq[i].set_raw("\xFF")
736
        elif mem.duplex == "split":
737
            _mem.txfreq = mem.offset / 10
738
        elif mem.duplex == "+":
739
            _mem.txfreq = (mem.freq + mem.offset) / 10
740
        elif mem.duplex == "-":
741
            _mem.txfreq = (mem.freq - mem.offset) / 10
742
        else:
743
            _mem.txfreq = mem.freq / 10
744

    
745
        _namelength = self.get_features().valid_name_length
746
        for i in range(_namelength):
747
            try:
748
                _nam.name[i] = mem.name[i]
749
            except IndexError:
750
                _nam.name[i] = "\xFF"
751

    
752
        rxmode = txmode = ""
753
        if mem.tmode == "Tone":
754
            tone = str(int(mem.rtone * 10)).rjust(4, '0')
755
            _mem.txtone = (int(tone[0])<<12) + (int(tone[1])<<8) + (int(tone[2])<<4) + int(tone[3])
756
            _mem.rxtone = 0
757
        elif mem.tmode == "TSQL":
758
            tone = str(int(mem.ctone * 10)).rjust(4, '0')
759
            _mem.txtone = (int(tone[0])<<12) + (int(tone[1])<<8) + (int(tone[2])<<4) + int(tone[3])
760
            _mem.rxtone = (int(tone[0])<<12) + (int(tone[1])<<8) + (int(tone[2])<<4) + int(tone[3])
761
        elif mem.tmode == "DTCS":
762
            rxmode = txmode = "DTCS"
763
            tone = str(int(mem.dtcs)).rjust(4, '0')
764
            _mem.txtone = 0x8000 + (int(tone[0])<<12) + (int(tone[1])<<8) + (int(tone[2])<<4) + int(tone[3])
765
            _mem.rxtone = 0x8000 + (int(tone[0])<<12) + (int(tone[1])<<8) + (int(tone[2])<<4) + int(tone[3])
766
        elif mem.tmode == "Cross":
767
            txmode, rxmode = mem.cross_mode.split("->", 1)
768
            if txmode == "Tone":
769
                tone = str(int(mem.rtone * 10)).rjust(4, '0')
770
                _mem.txtone = (int(tone[0])<<12) + (int(tone[1])<<8) + (int(tone[2])<<4) + int(tone[3])
771
            elif txmode == "DTCS":
772
                tone = str(int(mem.dtcs)).rjust(4, '0')
773
                _mem.txtone = 0x8000 + (int(tone[0])<<12) + (int(tone[1])<<8) + (int(tone[2])<<4) + int(tone[3])
774
            else:
775
                _mem.txtone = 0
776
            if rxmode == "Tone":
777
                tone = str(int(mem.ctone * 10)).rjust(4, '0')
778
                _mem.rxtone = (int(tone[0])<<12) + (int(tone[1])<<8) + (int(tone[2])<<4) + int(tone[3])
779
            elif rxmode == "DTCS":
780
                tone = str(int(mem.rx_dtcs)).rjust(4, '0')
781
                _mem.rxtone = 0x8000 + (int(tone[0])<<12) + (int(tone[1])<<8) + (int(tone[2])<<4) + int(tone[3])
782
            else:
783
                _mem.rxtone = 0
784
        else:
785
            _mem.rxtone = 0
786
            _mem.txtone = 0
787

    
788
        if txmode == "DTCS" and mem.dtcs_polarity[0] == "R":
789
            _mem.txtone += 0x4000
790
        if rxmode == "DTCS" and mem.dtcs_polarity[1] == "R":
791
            _mem.rxtone += 0x4000
792

    
793
        _mem.scan = mem.skip != "S"
794
        _mem.wide = mem.mode == "FM"
795

    
796
        if mem.power:
797
            _mem.lowpower = self.POWER_LEVELS.index(mem.power)
798
        else:
799
            _mem.lowpower = 0
800

    
801
        # extra settings
802
        if len(mem.extra) > 0:
803
            # there are setting, parse
804
            for setting in mem.extra:
805
                if setting.get_name() == "scode":
806
                    setattr(_mem, setting.get_name(), str(int(setting.value) + 1))
807
                else:
808
                    setattr(_mem, setting.get_name(), setting.value)
809
        else:
810
            # there are no extra settings, load defaults
811
            _mem.bcl = 0
812
            _mem.pttid = 0
813
            _mem.scode = 0
814

    
815

    
816
    def set_settings(self, settings):
817
        _settings = self._memobj.settings
818
        _mem = self._memobj
819
        for element in settings:
820
            if not isinstance(element, RadioSetting):
821
                if element.get_name() == "fm_preset":
822
                    self._set_fm_preset(element)
823
                else:
824
                    self.set_settings(element)
825
                    continue
826
            else:
827
                try:
828
                    name = element.get_name()
829
                    if "." in name:
830
                        bits = name.split(".")
831
                        obj = self._memobj
832
                        for bit in bits[:-1]:
833
                            if "/" in bit:
834
                                bit, index = bit.split("/", 1)
835
                                index = int(index)
836
                                obj = getattr(obj, bit)[index]
837
                            else:
838
                                obj = getattr(obj, bit)
839
                        setting = bits[-1]
840
                    else:
841
                        obj = _settings
842
                        setting = element.get_name()
843

    
844
                    if element.has_apply_callback():
845
                        LOG.debug("Using apply callback")
846
                        element.run_apply_callback()
847
                    elif element.value.get_mutable():
848
                        LOG.debug("Setting %s = %s" % (setting, element.value))
849
                        setattr(obj, setting, element.value)
850
                except Exception:
851
                    LOG.debug(element.get_name())
852
                    raise
853

    
854
    def _set_fm_preset(self, settings):
855
        for element in settings:
856
            try:
857
                val = element.value
858
                if self._memobj.fm_presets <= 108.0 * 10 - 650:
859
                    value = int(val.get_value() * 10 - 650)
860
                else:
861
                    value = int(val.get_value() * 10)
862
                LOG.debug("Setting fm_presets = %s" % (value))
863
                if self._bw_shift:
864
                    value = ((value & 0x00FF) << 8) | ((value & 0xFF00) >> 8)
865
                self._memobj.fm_presets = value
866
            except Exception:
867
                LOG.debug(element.get_name())
868
                raise
869

    
870
    @classmethod
871
    def match_model(cls, filedata, filename):
872
        match_size = False
873
        match_model = False
874

    
875
        # testing the file data size
876
        if len(filedata) in [0xC000]:
877
            match_size = True
878

    
879
        # testing the firmware model fingerprint
880
        match_model = model_match(cls, filedata)
881

    
882
        if match_size and match_model:
883
            return True
884
        else:
885
            return False
886

    
887

    
888

    
889

    
890

    
(2-2/3)