Project

General

Profile

New Model #10865 » baofeng_uv17.py

Sander van der Wel, 09/26/2023 09:04 AM

 
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 import errors, util
32

    
33
LOG = logging.getLogger(__name__)
34

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

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

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

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

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

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

    
82

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

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

    
96
    return data
97

    
98

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

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

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

    
123

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

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

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

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

    
142
    return data
143

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

    
158
    # Flush input buffer
159
    _clean_buffer(radio)
160

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

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

    
171
    return True
172

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
254
    return data
255

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

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

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

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

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

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

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

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

    
322

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

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

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

    
337

    
338
@directory.register
339

    
340
class UV17(chirp_common.CloneModeRadio, 
341
           chirp_common.ExperimentalRadio):
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 _is_txinh(self, _mem):
597
        raw_tx = ""
598
        for i in range(0, 4):
599
            raw_tx += _mem.txfreq[i].get_raw()
600
        return raw_tx == "\xFF\xFF\xFF\xFF"
601
    
602
    def get_memory(self, number):
603
        offset = 0
604
        #skip 16 bytes at memory block boundary
605
        if number >= 252:
606
            offset += 1
607
        if number >= 507:
608
            offset += 1
609
        if number >= 762:
610
            offset += 1
611

    
612
        _mem = self._memobj.memory[number + offset]
613
        _nam = self._memobj.names[number]
614

    
615
        mem = chirp_common.Memory()
616
        mem.number = number
617

    
618
        if _mem.get_raw()[0] == "\xff":
619
            mem.empty = True
620
            return mem
621

    
622
        mem.freq = int(_mem.rxfreq) * 10
623

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

    
645
        for char in _nam.name:
646
            if (str(char) == "\xFF") | (str(char) == "\x00"):
647
                char = " "  # The OEM software may have 0xFF mid-name
648
            mem.name += str(char)
649
        mem.name = mem.name.rstrip()
650

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

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

    
676
        if txmode == "Tone" and not rxmode:
677
            mem.tmode = "Tone"
678
        elif txmode == rxmode and txmode == "Tone" and mem.rtone == mem.ctone:
679
            mem.tmode = "TSQL"
680
        elif txmode == rxmode and txmode == "DTCS" and mem.dtcs == mem.rx_dtcs:
681
            mem.tmode = "DTCS"
682
        elif rxmode or txmode:
683
            mem.tmode = "Cross"
684
            mem.cross_mode = "%s->%s" % (txmode, rxmode)
685

    
686
        mem.dtcs_polarity = "".join(dtcs_pol)
687

    
688
        if not _mem.scan:
689
            mem.skip = "S"
690

    
691
        levels = self.POWER_LEVELS
692
        try:
693
            mem.power = levels[_mem.lowpower]
694
        except IndexError:
695
            LOG.error("Radio reported invalid power level %s (in %s)" %
696
                        (_mem.power, levels))
697
            mem.power = levels[0]
698

    
699
        mem.mode = _mem.wide and "FM" or "NFM"
700

    
701
        mem.extra = RadioSettingGroup("Extra", "extra")
702

    
703
        rs = RadioSetting("bcl", "BCL",
704
                          RadioSettingValueBoolean(_mem.bcl))
705
        mem.extra.append(rs)
706

    
707
        rs = RadioSetting("pttid", "PTT ID",
708
                          RadioSettingValueList(self.PTTID_LIST,
709
                                                self.PTTID_LIST[_mem.pttid]))
710
        mem.extra.append(rs)
711

    
712
        rs = RadioSetting("scode", "S-CODE",
713
                          RadioSettingValueList(self.SCODE_LIST,
714
                                                self.SCODE_LIST[_mem.scode - 1]))
715
        mem.extra.append(rs)
716

    
717
        return mem
718

    
719
    def set_memory(self, mem):
720
        offset = 0
721
        #skip 16 bytes at memory block boundary
722
        if mem.number >= 252:
723
            offset += 1
724
        if mem.number >= 507:
725
            offset += 1
726
        if mem.number >= 762:
727
            offset += 1
728
        _mem = self._memobj.memory[mem.number + offset]
729
        _nam = self._memobj.names[mem.number]
730

    
731
        if mem.empty:
732
            _mem.set_raw("\xff" * 16)
733
            _nam.set_raw("\xff" * 16)
734
            return
735

    
736
        _mem.set_raw("\x00" * 16)
737
        _mem.rxfreq = mem.freq / 10
738
        
739
        if mem.duplex == "off":
740
            for i in range(0, 4):
741
                _mem.txfreq[i].set_raw("\xFF")
742
        elif mem.duplex == "split":
743
            _mem.txfreq = mem.offset / 10
744
        elif mem.duplex == "+":
745
            _mem.txfreq = (mem.freq + mem.offset) / 10
746
        elif mem.duplex == "-":
747
            _mem.txfreq = (mem.freq - mem.offset) / 10
748
        else:
749
            _mem.txfreq = mem.freq / 10
750

    
751
        _namelength = self.get_features().valid_name_length
752
        for i in range(_namelength):
753
            try:
754
                _nam.name[i] = mem.name[i]
755
            except IndexError:
756
                _nam.name[i] = "\xFF"
757

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

    
794
        if txmode == "DTCS" and mem.dtcs_polarity[0] == "R":
795
            _mem.txtone += 0x4000
796
        if rxmode == "DTCS" and mem.dtcs_polarity[1] == "R":
797
            _mem.rxtone += 0x4000
798

    
799
        _mem.scan = mem.skip != "S"
800
        _mem.wide = mem.mode == "FM"
801

    
802
        if mem.power:
803
            _mem.lowpower = self.POWER_LEVELS.index(mem.power)
804
        else:
805
            _mem.lowpower = 0
806

    
807
        # extra settings
808
        if len(mem.extra) > 0:
809
            # there are setting, parse
810
            for setting in mem.extra:
811
                if setting.get_name() == "scode":
812
                    setattr(_mem, setting.get_name(), str(int(setting.value) + 1))
813
                else:
814
                    setattr(_mem, setting.get_name(), setting.value)
815
        else:
816
            # there are no extra settings, load defaults
817
            _mem.bcl = 0
818
            _mem.pttid = 0
819
            _mem.scode = 0
820

    
821

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

    
850
                    if element.has_apply_callback():
851
                        LOG.debug("Using apply callback")
852
                        element.run_apply_callback()
853
                    elif element.value.get_mutable():
854
                        LOG.debug("Setting %s = %s" % (setting, element.value))
855
                        setattr(obj, setting, element.value)
856
                except Exception:
857
                    LOG.debug(element.get_name())
858
                    raise
859

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

    
876
    @classmethod
877
    def match_model(cls, filedata, filename):
878
        match_size = False
879
        match_model = False
880

    
881
        # testing the file data size
882
        if len(filedata) in [0xC000]:
883
            match_size = True
884

    
885
        # testing the firmware model fingerprint
886
        match_model = model_match(cls, filedata)
887

    
888
        if match_size and match_model:
889
            return True
890
        else:
891
            return False
892

    
893

    
894

    
895

    
896

    
(1-1/3)