Project

General

Profile

New Model #1035 » th9000-v0.8.patch

patch file - David Fannin, 05/10/2015 06:16 PM

View differences:

/dev/null Thu Jan 01 00:00:00 1970 +0000 → chirp/drivers/th9000.py Sun May 10 18:11:21 2015 -0700
1
# Copyright 2015 David Fannin KK6DF  <kk6df@arrl.org>
2
#
3
# This program is free software: you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation, either version 2 of the License, or
6
# (at your option) any later version.
7
#
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
12
#
13
# You should have received a copy of the GNU General Public License
14
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
15

  
16
import os
17
import struct
18
import time
19
import logging
20

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

  
32
LOG = logging.getLogger(__name__)
33

  
34
#
35
#  Chirp Driver for TYT TH-9000D (models: 2M (144 Mhz), 1.25M (220 Mhz)  and 70cm (440 Mhz)  radios)
36
#
37
#  Version 1.0 
38
#
39
#         - Skip channels
40
#
41
# Global Parameters 
42
#
43
MMAPSIZE = 16384
44
TONES = [62.5] + list(chirp_common.TONES)
45
TMODES =  ['','Tone','DTCS',''] 
46
DUPLEXES = ['','err','-','+'] # index 2 not used
47
MODES = ['WFM','FM','NFM']  #  25k, 20k,15k bw 
48
TUNING_STEPS=[ 5.0, 6.25, 8.33, 10.0, 12.5, 15.0, 20.0, 25.0, 30.0, 50.0 ] # index 0-9
49
POWER_LEVELS=[chirp_common.PowerLevel("High", watts=65),
50
              chirp_common.PowerLevel("Mid", watts=25),
51
              chirp_common.PowerLevel("Low", watts=10)]
52

  
53
CROSS_MODES = chirp_common.CROSS_MODES
54

  
55
APO_LIST = [ "Off","30 min","1 hr","2 hrs" ] 
56
BGCOLOR_LIST = ["Blue","Orange","Purple"]
57
BGBRIGHT_LIST = ["%s" % x for x in range(1,32)]
58
SQUELCH_LIST = ["Off"] + ["Level %s" % x for x in range(1,20)] 
59
TIMEOUT_LIST = ["Off"] + ["%s min" % x for x in range(1,30)]
60
TXPWR_LIST = ["60W","25W"]  # maximum power for Hi setting
61
TBSTFREQ_LIST = ["1750Hz","2100Hz","1000Hz","1450Hz"]
62
BEEP_LIST = ["Off","On"]
63

  
64
SETTING_LISTS = {
65
        "auto_power_off": APO_LIST,
66
        "bg_color"      : BGCOLOR_LIST,
67
        "bg_brightness" : BGBRIGHT_LIST,
68
        "squelch"       : SQUELCH_LIST,
69
        "timeout_timer" : TIMEOUT_LIST,
70
        "choose_tx_power": TXPWR_LIST,
71
        "tbst_freq"     : TBSTFREQ_LIST,
72
        "voice_prompt"  : BEEP_LIST
73
}
74

  
75
MEM_FORMAT = """
76
#seekto 0x0000;
77
struct {
78
   u8 unknown0000[16];
79
   char idhdr[16];
80
   u8 unknown0001[16];
81
} fidhdr;
82
"""
83
#Overall Memory Map:
84
#
85
#    Memory Map (Range 0x0100-3FF0, step 0x10):
86
#
87
#        Field                   Start  End  Size   
88
#                                (hex)  (hex) (hex)  
89
#        
90
#        1 Channel Set Flag        0100  011F   20 
91
#        2 Channel Skip Flag       0120  013F   20 
92
#        3 Blank/Unknown           0140  01EF   B0 
93
#        4 Unknown                 01F0  01FF   10
94
#        5 TX/RX Range             0200  020F   10    
95
#        6 Bootup Passwd           0210  021F   10 
96
#        7 Options, Radio          0220  023F   20
97
#        8 Unknown                 0240  019F   
98
#            8B Startup Label      03E0  03E7   07
99
#        9 Channel Bank            2000  38FF 1900  
100
#             Channel 000          2000  201F   20  
101
#             Channel 001          2020  202F   20  
102
#             ... 
103
#             Channel 199          38E0  38FF   20 
104
#        10 Blank/Unknown          3900  3FFF  6FF  14592  16383    1792   
105
#            Total Map Size           16128 (2^8 = 16384)
106
#
107
#  TH9000/220  memory map 
108
#  section: 1 and 2:  Channel Set/Skip Flags
109
# 
110
#    Channel Set (starts 0x100) : Channel Set  bit is value 0 if a memory location in the channel bank is active.
111
#    Channel Skip (starts 0x120): Channel Skip bit is value 0 if a memory location in the channel bank is active.
112
#
113
#    Both flag maps are a total 24 bytes in length, aligned on 32 byte records.
114
#    bit = 0 channel set/no skip,  1 is channel not set/skip
115
#
116
#    to index a channel:
117
#        cbyte = channel / 8 ;
118
#        cbit  = channel % 8 ;
119
#        setflag  = csetflag[cbyte].c[cbit] ;
120
#        skipflag = cskipflag[cbyte].c[cbit] ;
121
#
122
#    channel range is 0-199, range is 32 bytes (last 7 unknown)
123
#
124
MEM_FORMAT = MEM_FORMAT + """
125
#seekto 0x0100;
126
struct {
127
   bit c[8];
128
} csetflag[32];
129

  
130
struct {
131
   u8 unknown0100[7];
132
} ropt0100;
133

  
134
#seekto 0x0120;
135
struct {
136
   bit c[8];
137
} cskipflag[32];
138

  
139
struct {
140
   u8 unknown0120[7];
141
} ropt0120;
142
"""
143
#  TH9000  memory map 
144
#  section: 5  TX/RX Range
145
#     used to set the TX/RX range of the radio (e.g.  222-228Mhz for 220 meter)
146
#     possible to set range for tx/rx 
147
#
148
MEM_FORMAT = MEM_FORMAT + """
149
#seekto 0x0200;
150
struct {
151
    bbcd txrangelow[4];
152
    bbcd txrangehi[4];
153
    bbcd rxrangelow[4];
154
    bbcd rxrangehi[4];
155
} freqrange;
156
"""
157
# TH9000  memory map 
158
# section: 6  bootup_passwd
159
#    used to set bootup passwd (see boot_passwd checkbox option)
160
#
161
#  options - bootup password
162
#
163
#  bytes:bit   type                 description
164
#  ---------------------------------------------------------------------------
165
#  6         u8 bootup_passwd[6]     bootup passwd, 6 chars, numberic chars 30-39 , see boot_passwd checkbox to set
166
#  10        u8 unknown;  
167
#
168

  
169
MEM_FORMAT = MEM_FORMAT + """
170
#seekto 0x0210;
171
struct {
172
   u8 bootup_passwd[6];
173
   u8 unknown2010[10];
174
} ropt0210;
175
"""
176
#  TH9000/220  memory map 
177
#  section: 7  Radio Options  
178
#        used to set a number of radio options 
179
#
180
#  bytes:bit   type                 description
181
#  ---------------------------------------------------------------------------
182
#  1         u8 display_mode     display mode, range 0-2, 0=freq,1=channel,2=name (selecting name affects vfo_mr)
183
#  1         u8 vfo_mr;          vfo_mr , 0=vfo, mr=1 
184
#  1         u8 unknown;  
185
#  1         u8 squelch;         squelch level, range 0-19, hex for menu
186
#  1         u8 unknown[2]; 
187
#  1         u8 channel_lock;    if display_mode[channel] selected, then lock=1,no lock =0
188
#  1         u8 unknown; 
189
#  1         u8 bg_brightness ;  background brightness, range 0-21, hex, menu index 
190
#  1         u8 unknown;     
191
#  1         u8 bg_color ;       bg color, menu index,  blue 0 , orange 1, purple 2
192
#  1         u8 tbst_freq ;      tbst freq , menu 0 = 1750Hz, 1=2100 , 2=1000 , 3=1450hz 
193
#  1         u8 timeout_timer;   timeout timer, hex, value = minutes, 0= no timeout
194
#  1         u8 unknown; 
195
#  1         u8 auto_power_off;   auto power off, range 0-3, off,30min, 1hr, 2hr, hex menu index
196
#  1         u8 voice_prompt;     voice prompt, value 0,1 , Beep ON = 1, Beep Off = 2
197
#
198
# description of function setup options, starting at 0x0230
199
#
200
#  bytes:bit   type                 description
201
#  ---------------------------------------------------------------------------
202
#  1         u8  // 0
203
#   :4       unknown:6
204
#   :1       elim_sql_tail:1   eliminate squelsh tail when no ctcss checkbox (1=checked)
205
#   :1       sql_key_function  "squelch off" 1 , "squelch momentary off" 0 , menu index
206
#  2         u8 unknown[2] /1-2  
207
#  1         u8 // 3
208
#   :4       unknown:4
209
#   :1       inhibit_init_ops:1 //bit 5
210
#   :1       unknownD:1
211
#   :1       inhibit_setup_bg_chk:1 //bit 7
212
#   :1       unknown:1
213
#  1         u8 tail_elim_type    menu , (off=0,120=1,180=2),  // 4
214
#  1         u8 choose_tx_power    menu , (60w=0,25w=1) // 5
215
#  2         u8 unknown[2]; // 6-7 
216
#  1         u8 bootup_passwd_flag  checkbox 1=on, 0=off // 8
217
#  7         u8 unknown[7]; // 9-F 
218
#
219
MEM_FORMAT = MEM_FORMAT + """
220
#seekto 0x0220;
221
struct {
222
   u8 display_mode; 
223
   u8 vfo_mr; 
224
   u8 unknown0220A; 
225
   u8 squelch; 
226
   u8 unknown0220B[2]; 
227
   u8 channel_lock; 
228
   u8 unknown0220C; 
229
   u8 bg_brightness; 
230
   u8 unknown0220D; 
231
   u8 bg_color;
232
   u8 tbst_freq;
233
   u8 timeout_timer;
234
   u8 unknown0220E;
235
   u8 auto_power_off;
236
   u8 voice_prompt; 
237
   u8 unknown0230A:6,
238
      elim_sql_tail:1,
239
      sql_key_function:1;
240
   u8 unknown0230B[2];
241
   u8 unknown0230C:4, 
242
      inhibit_init_ops:1,
243
      unknown0230D:1,
244
      inhibit_setup_bg_chk:1,
245
      unknown0230E:1;
246
   u8 tail_elim_type;
247
   u8 choose_tx_power;
248
   u8 unknown0230F[2];
249
   u8 bootup_passwd_flag;
250
   u8 unknown0230G[7];
251
} settings;
252
"""
253
#  TH9000  memory map 
254
#  section: 8B  Startup Label  
255
#
256
#  bytes:bit   type                 description
257
#  ---------------------------------------------------------------------------
258
#  7     char start_label[7]    label displayed at startup (usually your call sign)
259
#
260
MEM_FORMAT = MEM_FORMAT + """
261
#seekto 0x03E0;
262
struct {
263
    char startname[7];
264
} slabel;
265
"""
266
#  TH9000/220  memory map 
267
#  section: 9  Channel Bank
268
#         description of channel bank (200 channels , range 0-199)
269
#         Each 32 Byte (0x20 hex)  record:
270
#  bytes:bit   type                 description
271
#  ---------------------------------------------------------------------------
272
#  4         bbcd freq[4]        receive frequency in packed binary coded decimal  
273
#  4         bbcd offset[4]      transmit offset in packed binary coded decimal (note: plus/minus direction set by 'duplex' field)
274
#  1         u8
275
#   :4       unknown:4
276
#   :4       tuning_step:4         tuning step, menu index value from 0-9
277
#            5,6.25,8.33,10,12.5,15,20,25,30,50
278
#  1         u8
279
#   :4       unknown:4          not yet decoded, used for DCS coding?
280
#   :2       channel_width:2     channel spacing, menu index value from 0-3
281
#            25,20,12.5
282
#   :1       reverse:1           reverse flag, 0=off, 1=on (reverses tx and rx freqs)
283
#   :1       txoff:1             transmitt off flag, 0=transmit , 1=do not transmit 
284
#  1         u8
285
#   :1       talkaround:1        talkaround flag, 0=off, 1=on (bypasses repeater) 
286
#   :1       compander:1         compander flag, 0=off, 1=on (turns on/off voice compander option)  
287
#   :2       unknown:2          
288
#   :2       power:2             tx power setting, value range 0-2, 0=hi,1=med,2=lo 
289
#   :2       duplex:2            duplex settings, 0=simplex,2= minus(-) offset, 3= plus (+) offset (see offset field) 
290
#            
291
#  1         u8 
292
#   :4       unknown:4
293
#   :2       rxtmode:2           rx tone mode, value range 0-2, 0=none, 1=CTCSS, 2=DCS  (ctcss tone in field rxtone)
294
#   :2       txtmode:2           tx tone mode, value range 0-2, 0=none, 1=CTCSS, 3=DCS  (ctcss tone in field txtone)
295
#  1         u8 
296
#   :2       unknown:2
297
#   :6       txtone:6            tx ctcss tone, menu index
298
#  1         u8 
299
#   :2       unknown:2 
300
#   :6       rxtone:6            rx ctcss tone, menu index
301
#  1         u8 txcode           ?, not used for ctcss
302
#  1         u8 rxcode           ?, not used for ctcss
303
#  3         u8 unknown[3]
304
#  7         char name[7]        7 byte char string for channel name
305
#  1         u8 
306
#   :6       unknown:6,
307
#   :2       busychannellockout:2 busy channel lockout option , 0=off, 1=repeater, 2=busy  (lock out tx if channel busy)
308
#  4         u8 unknownI[4];
309
#  1         u8 
310
#   :7       unknown:7 
311
#   :1       scrambler:1         scrambler flag, 0=off, 1=on (turns on tyt scrambler option)
312
#
313
MEM_FORMAT = MEM_FORMAT + """
314
#seekto 0x2000;
315
struct {
316
  bbcd freq[4];
317
  bbcd offset[4];
318
  u8 unknown2000A:4,
319
     tuning_step:4;
320
  u8 rxdcsextra:1,
321
     txdcsextra:1,
322
     rxinv:1,
323
     txinv:1,
324
     channel_width:2,
325
     reverse:1,
326
     txoff:1;
327
  u8 talkaround:1,
328
     compander:1,
329
     unknown2000C:2,
330
     power:2,
331
     duplex:2;
332
  u8 unknown2000D:4,
333
     rxtmode:2,
334
     txtmode:2;
335
  u8 unknown2000E:2,
336
     txtone:6;
337
  u8 unknown2000F:2,
338
     rxtone:6;
339
  u8 txcode;
340
  u8 rxcode;
341
  u8 unknown2000G[3];
342
  char name[7];
343
  u8 unknown2000H:6,
344
     busychannellockout:2;
345
  u8 unknown2000I[4];
346
  u8 unknown2000J:7,
347
     scrambler:1; 
348
} memory[200] ;
349
"""
350

  
351
def _echo_write(radio, data):
352
    try:
353
        radio.pipe.write(data)
354
        radio.pipe.read(len(data))
355
    except Exception, e:
356
        LOG.error("Error writing to radio: %s" % e)
357
        raise errors.RadioError("Unable to write to radio")
358

  
359

  
360
def _checksum(data):
361
    cs = 0
362
    for byte in data:
363
        cs += ord(byte)
364
    return cs % 256
365

  
366
def _read(radio, length):
367
    try:
368
        data = radio.pipe.read(length)
369
    except Exception, e:
370
        LOG.error( "Error reading from radio: %s" % e)
371
        raise errors.RadioError("Unable to read from radio")
372

  
373
    if len(data) != length:
374
        LOG.error( "Short read from radio (%i, expected %i)" % (len(data),
375
                                                           length))
376
        LOG.debug(util.hexprint(data))
377
        raise errors.RadioError("Short read from radio")
378
    return data
379

  
380

  
381

  
382
def _ident(radio):
383
    radio.pipe.setTimeout(1)
384
    _echo_write(radio,"PROGRAM")
385
    response = radio.pipe.read(3)
386
    if response != "QX\06":
387
        LOG.debug( "Response was :\n%s" % util.hexprint(response))
388
        raise errors.RadioError("Unsupported model")
389
    _echo_write(radio, "\x02")
390
    response = radio.pipe.read(16)
391
    LOG.debug(util.hexprint(response))
392
    if response[1:8] != "TH-9000":
393
        LOG.error( "Looking  for:\n%s" % util.hexprint("TH-9000"))
394
        LOG.error( "Response was:\n%s" % util.hexprint(response))
395
        raise errors.RadioError("Unsupported model")
396

  
397
def _send(radio, cmd, addr, length, data=None):
398
    frame = struct.pack(">cHb", cmd, addr, length)
399
    if data:
400
        frame += data
401
        frame += chr(_checksum(frame[1:]))
402
        frame += "\x06"
403
    _echo_write(radio, frame)
404
    LOG.debug("Sent:\n%s" % util.hexprint(frame))
405
    if data:
406
        result = radio.pipe.read(1)
407
        if result != "\x06":
408
            LOG.debug( "Ack was: %s" % repr(result))
409
            raise errors.RadioError("Radio did not accept block at %04x" % addr)
410
        return
411
    result = _read(radio, length + 6)
412
    LOG.debug("Got:\n%s" % util.hexprint(result))
413
    header = result[0:4]
414
    data = result[4:-2]
415
    ack = result[-1]
416
    if ack != "\x06":
417
        LOG.debug("Ack was: %s" % repr(ack))
418
        raise errors.RadioError("Radio NAK'd block at %04x" % addr)
419
    _cmd, _addr, _length = struct.unpack(">cHb", header)
420
    if _addr != addr or _length != _length:
421
        LOG.debug( "Expected/Received:")
422
        LOG.debug(" Length: %02x/%02x" % (length, _length))
423
        LOG.debug( " Addr: %04x/%04x" % (addr, _addr))
424
        raise errors.RadioError("Radio send unexpected block")
425
    cs = _checksum(result[1:-2])
426
    if cs != ord(result[-2]):
427
        LOG.debug( "Calculated: %02x" % cs)
428
        LOG.debug( "Actual:     %02x" % ord(result[-2]))
429
        raise errors.RadioError("Block at 0x%04x failed checksum" % addr)
430
    return data
431

  
432

  
433
def _finish(radio):
434
    endframe = "\x45\x4E\x44"
435
    _echo_write(radio, endframe)
436
    result = radio.pipe.read(1)
437
    if result != "\x06":
438
        LOG.error( "Got:\n%s" % util.hexprint(result))
439
        raise errors.RadioError("Radio did not finish cleanly")
440

  
441
def do_download(radio):
442

  
443
    _ident(radio)
444

  
445
    _memobj = None
446
    data = ""
447

  
448
    for start,end in radio._ranges: 
449
        for addr in range(start,end,0x10):
450
            block = _send(radio,'R',addr,0x10) 
451
            data += block
452
            status = chirp_common.Status()
453
            status.cur = len(data)
454
            status.max = end
455
            status.msg = "Downloading from radio"
456
            radio.status_fn(status)
457

  
458
    _finish(radio)
459

  
460
    return memmap.MemoryMap(data)
461

  
462
def do_upload(radio):
463

  
464
    _ident(radio)
465

  
466
    for start,end in radio._ranges:
467
        for addr in range(start,end,0x10):
468
            if addr < 0x0100:
469
                continue
470
            block = radio._mmap[addr:addr+0x10]
471
            _send(radio,'W',addr,len(block),block)
472
            status = chirp_common.Status()
473
            status.cur = addr
474
            status.max = end
475
            status.msg = "Uploading to Radio"
476
            radio.status_fn(status)
477

  
478
    _finish(radio)
479
            
480

  
481

  
482
#
483
# The base class, extended for use with other models
484
#
485
class Th9000Radio(chirp_common.CloneModeRadio,
486
                  chirp_common.ExperimentalRadio):
487
    """TYT TH-9000"""
488
    VENDOR = "TYT"    
489
    MODEL = "TH9000 Base" 
490
    BAUD_RATE = 9600 
491
    valid_freq = [(900000000, 999000000)]
492
    
493

  
494
    _memsize = MMAPSIZE
495
    _ranges = [(0x0000,0x4000)]
496

  
497
    @classmethod
498
    def get_prompts(cls):
499
        rp = chirp_common.RadioPrompts()
500
        rp.experimental = ("The TYT TH-9000 driver is an beta version."
501
                           "Proceed with Caution and backup your data")
502
        return rp
503

  
504
    def get_features(self):
505
        rf = chirp_common.RadioFeatures()
506
        rf.has_settings = True
507
        rf.has_bank = False
508
        rf.has_cross = True
509
        rf.has_tuning_step = False
510
        rf.has_rx_dtcs = True
511
        rf.valid_skips = ["","S"]
512
        rf.memory_bounds = (0, 199) 
513
        rf.valid_name_length = 7
514
        rf.valid_characters = chirp_common.CHARSET_UPPER_NUMERIC + "-"
515
        rf.valid_modes = MODES
516
        rf.valid_tmodes = ['','Tone','TSQL','DTCS','Cross']
517
        rf.valid_cross_modes = ['Tone->DTCS','DTCS->Tone',
518
                               '->Tone','->DTCS','Tone->Tone']
519
        rf.valid_power_levels = POWER_LEVELS
520
        rf.valid_dtcs_codes = chirp_common.ALL_DTCS_CODES
521
        rf.valid_bands = self.valid_freq
522
        return rf
523

  
524
    # Do a download of the radio from the serial port
525
    def sync_in(self):
526
        self._mmap = do_download(self)
527
        self.process_mmap()
528

  
529
    # Do an upload of the radio to the serial port
530
    def sync_out(self):
531
        do_upload(self)
532

  
533
    def process_mmap(self):
534
        self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
535

  
536

  
537
    # Return a raw representation of the memory object, which 
538
    # is very helpful for development
539
    def get_raw_memory(self, number):
540
        return repr(self._memobj.memory[number])
541

  
542
    # not working yet
543
    def _get_dcs_index(self, _mem,which):
544
        base = getattr(_mem, '%scode' % which)
545
        extra = getattr(_mem, '%sdcsextra' % which)
546
        return (int(extra) << 8) | int(base)
547

  
548
    def _set_dcs_index(self, _mem, which, index):
549
        base = getattr(_mem, '%scode' % which)
550
        extra = getattr(_mem, '%sdcsextra' % which)
551
        base.set_value(index & 0xFF)
552
        extra.set_value(index >> 8)
553

  
554

  
555
    # Extract a high-level memory object from the low-level memory map
556
    # This is called to populate a memory in the UI
557
    def get_memory(self, number):
558
        # Get a low-level memory object mapped to the image
559
        _mem = self._memobj.memory[number]
560

  
561
        # get flag info
562
        cbyte = number / 8 ;
563
        cbit =  7 - (number % 8) ;
564
        setflag = self._memobj.csetflag[cbyte].c[cbit]; 
565
        skipflag = self._memobj.cskipflag[cbyte].c[cbit]; 
566

  
567
        mem = chirp_common.Memory()
568

  
569
        mem.number = number  # Set the memory number
570

  
571
        if setflag == 1:
572
            mem.empty = True
573
            return mem
574

  
575
        mem.freq = int(_mem.freq) * 100    
576
        mem.offset = int(_mem.offset) * 100
577
        mem.name = str(_mem.name).rstrip() # Set the alpha tag
578
        mem.duplex = DUPLEXES[_mem.duplex]
579
        mem.mode = MODES[_mem.channel_width]
580
        mem.power = POWER_LEVELS[_mem.power]
581

  
582
        rxtone = txtone = None
583

  
584

  
585
        rxmode = TMODES[_mem.rxtmode]
586
        txmode = TMODES[_mem.txtmode]
587

  
588

  
589

  
590
        # doesn't work
591
        if rxmode == "Tone":
592
            rxtone = TONES[_mem.rxtone]
593
        elif rxmode == "DTCS":
594
            rxtone = chirp_common.ALL_DTCS_CODES[self._get_dcs_index(_mem,'rx')]
595

  
596
        if txmode == "Tone":
597
            txtone = TONES[_mem.txtone]
598
        elif txmode == "DTCS":
599
            txtone = chirp_common.ALL_DTCS_CODES[self._get_dcs_index(_mem,'tx')]
600

  
601
        rxpol = _mem.rxinv and "R" or "N"
602
        txpol = _mem.txinv and "R" or "N"
603

  
604
        chirp_common.split_tone_decode(mem,
605
                                       (txmode, txtone, txpol),
606
                                       (rxmode, rxtone, rxpol))
607

  
608
        mem.skip = "S" if skipflag == 1 else ""
609

  
610

  
611
        # We'll consider any blank (i.e. 0MHz frequency) to be empty
612
        if mem.freq == 0:
613
            mem.empty = True
614

  
615
        return mem
616

  
617
    # Store details about a high-level memory to the memory map
618
    # This is called when a user edits a memory in the UI
619
    def set_memory(self, mem):
620
        # Get a low-level memory object mapped to the image
621

  
622
        _mem = self._memobj.memory[mem.number]
623

  
624
        cbyte = mem.number / 8 
625
        cbit =  7 - (mem.number % 8) 
626

  
627
        if mem.empty:
628
            self._memobj.csetflag[cbyte].c[cbit] = 1
629
            self._memobj.cskipflag[cbyte].c[cbit] = 1
630
            return
631

  
632
        self._memobj.csetflag[cbyte].c[cbit] =  0 
633
        self._memobj.cskipflag[cbyte].c[cbit]  =  1 if (mem.skip == "S") else 0
634

  
635
        _mem.set_raw("\x00" * 32)
636

  
637
        _mem.freq = mem.freq / 100         # Convert to low-level frequency
638
        _mem.offset = mem.offset / 100         # Convert to low-level frequency
639

  
640
        _mem.name = mem.name.ljust(7)[:7]  # Store the alpha tag
641
        _mem.duplex = DUPLEXES.index(mem.duplex)
642

  
643

  
644
        try:
645
            _mem.channel_width = MODES.index(mem.mode)
646
        except ValueError:
647
            _mem.channel_width = 0
648

  
649
        ((txmode, txtone, txpol),
650
         (rxmode, rxtone, rxpol)) = chirp_common.split_tone_encode(mem)
651

  
652
        _mem.txtmode = TMODES.index(txmode)
653

  
654
        _mem.rxtmode = TMODES.index(rxmode)
655

  
656
        if txmode == "Tone":
657
            _mem.txtone = TONES.index(txtone)
658
        elif txmode == "DTCS":
659
            self._set_dcs_index(_mem,'tx',chirp_common.ALL_DTCS_CODES.index(txtone))
660

  
661
        if rxmode == "Tone":
662
            _mem.rxtone = TONES.index(rxtone)
663
        elif rxmode == "DTCS":
664
            self._set_dcs_index(_mem, 'rx', chirp_common.ALL_DTCS_CODES.index(rxtone))
665

  
666
        _mem.txinv = txpol == "R"
667
        _mem.rxinv = rxpol == "R"
668

  
669
       
670
        if mem.power:
671
            _mem.power = POWER_LEVELS.index(mem.power)
672
        else:
673
            _mem.power = 0
674

  
675
    def _get_settings(self):
676
        _settings = self._memobj.settings
677
        _freqrange = self._memobj.freqrange
678
        _slabel = self._memobj.slabel
679

  
680
        basic = RadioSettingGroup("basic","Global Settings")
681
        freqrange = RadioSettingGroup("freqrange","Frequency Ranges")
682
        top = RadioSettingGroup("top","All Settings",basic,freqrange)
683
        settings = RadioSettings(top)
684

  
685
        def _filter(name):
686
            filtered = ""
687
            for char in str(name):
688
                if char in chirp_common.CHARSET_ASCII:
689
                    filtered += char
690
                else:
691
                    filtered += ""
692
            return filtered
693
                   
694
        val = RadioSettingValueString(0,7,_filter(_slabel.startname))
695
        rs = RadioSetting("startname","Startup Label",val)
696
        basic.append(rs)
697

  
698
        rs = RadioSetting("bg_color","LCD Color",
699
                           RadioSettingValueList(BGCOLOR_LIST, BGCOLOR_LIST[_settings.bg_color]))
700
        basic.append(rs)
701

  
702
        rs = RadioSetting("bg_brightness","LCD Brightness",
703
                           RadioSettingValueList(BGBRIGHT_LIST, BGBRIGHT_LIST[_settings.bg_brightness]))
704
        basic.append(rs)
705

  
706
        rs = RadioSetting("squelch","Squelch Level",
707
                           RadioSettingValueList(SQUELCH_LIST, SQUELCH_LIST[_settings.squelch]))
708
        basic.append(rs)
709

  
710
        rs = RadioSetting("timeout_timer","Timeout Timer (TOT)",
711
                           RadioSettingValueList(TIMEOUT_LIST, TIMEOUT_LIST[_settings.timeout_timer]))
712
        basic.append(rs)
713

  
714
        rs = RadioSetting("auto_power_off","Auto Power Off (APO)",
715
                           RadioSettingValueList(APO_LIST, APO_LIST[_settings.auto_power_off]))
716
        basic.append(rs)
717

  
718
        rs = RadioSetting("voice_prompt","Beep Prompt",
719
                           RadioSettingValueList(BEEP_LIST, BEEP_LIST[_settings.voice_prompt]))
720
        basic.append(rs)
721

  
722
        rs = RadioSetting("tbst_freq","Tone Burst Frequency",
723
                           RadioSettingValueList(TBSTFREQ_LIST, TBSTFREQ_LIST[_settings.tbst_freq]))
724
        basic.append(rs)
725

  
726
        rs = RadioSetting("choose_tx_power","Max Level of TX Power",
727
                           RadioSettingValueList(TXPWR_LIST, TXPWR_LIST[_settings.choose_tx_power]))
728
        basic.append(rs)
729

  
730
        (flow,fhigh)  = self.valid_freq[0]
731
        flow  /= 1000
732
        fhigh /= 1000
733
        fmidrange = (fhigh- flow)/2
734

  
735
        rs = RadioSetting("txrangelow","TX Freq, Lower Limit (khz)", RadioSettingValueInteger(flow,
736
            flow + fmidrange,
737
            int(_freqrange.txrangelow)/10))
738
        freqrange.append(rs)
739

  
740
        rs = RadioSetting("txrangehi","TX Freq, Upper Limit (khz)", RadioSettingValueInteger(fhigh-fmidrange,
741
            fhigh,
742
            int(_freqrange.txrangehi)/10))
743
        freqrange.append(rs)
744

  
745
        rs = RadioSetting("rxrangelow","RX Freq, Lower Limit (khz)", RadioSettingValueInteger(flow,
746
            flow+fmidrange,
747
            int(_freqrange.rxrangelow)/10))
748
        freqrange.append(rs)
749

  
750
        rs = RadioSetting("rxrangehi","RX Freq, Upper Limit (khz)", RadioSettingValueInteger(fhigh-fmidrange,
751
            fhigh,
752
            int(_freqrange.rxrangehi)/10))
753
        freqrange.append(rs)
754

  
755
        return settings
756

  
757
    def get_settings(self):
758
        try:
759
            return self._get_settings()
760
        except:
761
            import traceback
762
            LOG.error( "failed to parse settings")
763
            traceback.print_exc()
764
            return None
765

  
766
    def set_settings(self,settings):
767
        _settings = self._memobj.settings
768
        for element in settings:
769
            if not isinstance(element,RadioSetting):
770
                self.set_settings(element)
771
                continue
772
            else:
773
                try:
774
                    name = element.get_name()
775

  
776
                    if  name in ["txrangelow","txrangehi","rxrangelow","rxrangehi"]:
777
                        LOG.debug( "setting %s = %s" % (name,int(element.value)*10))
778
                        setattr(self._memobj.freqrange,name,int(element.value)*10)
779
                        continue
780

  
781
                    if name in ["startname"]:
782
                        LOG.debug( "setting %s = %s" % (name, element.value))
783
                        setattr(self._memobj.slabel,name,element.value)
784
                        continue
785

  
786
                    obj = _settings
787
                    setting = element.get_name()
788

  
789
                    if element.has_apply_callback():
790
                        LOG.debug( "using apply callback")
791
                        element.run_apply_callback()
792
                    else:
793
                        LOG.debug( "Setting %s = %s" % (setting, element.value))
794
                        setattr(obj, setting, element.value)
795
                except Exception, e:
796
                    LOG.debug( element.get_name())
797
                    raise
798

  
799
    @classmethod
800
    def match_model(cls, filedata, filename):
801
        if  MMAPSIZE == len(filedata):
802
           (flow,fhigh)  = cls.valid_freq[0]
803
           flow  /= 1000000
804
           fhigh /= 1000000
805

  
806
           txmin=ord(filedata[0x200])*100 + (ord(filedata[0x201])>>4)*10 + ord(filedata[0x201])%16
807
           txmax=ord(filedata[0x204])*100 + (ord(filedata[0x205])>>4)*10 + ord(filedata[0x205])%16
808
           rxmin=ord(filedata[0x208])*100 + (ord(filedata[0x209])>>4)*10 + ord(filedata[0x209])%16
809
           rxmax=ord(filedata[0x20C])*100 + (ord(filedata[0x20D])>>4)*10 + ord(filedata[0x20D])%16
810

  
811
           if ( rxmin >= flow and rxmax <= fhigh and txmin >= flow and txmax <= fhigh ):
812
                return True
813

  
814
        return False
815

  
816
@directory.register
817
class Th9000220Radio(Th9000Radio):
818
    """TYT TH-9000 220"""
819
    VENDOR = "TYT"    
820
    MODEL = "TH9000_220" 
821
    BAUD_RATE = 9600 
822
    valid_freq = [(220000000, 260000000)]
823

  
824
@directory.register
825
class Th9000144Radio(Th9000220Radio):
826
    """TYT TH-9000 144"""
827
    VENDOR = "TYT"    
828
    MODEL = "TH9000_144" 
829
    BAUD_RATE = 9600 
830
    valid_freq = [(136000000, 174000000)]
831

  
832
@directory.register
833
class Th9000440Radio(Th9000220Radio):
834
    """TYT TH-9000 440"""
835
    VENDOR = "TYT"    
836
    MODEL = "TH9000_440" 
837
    BAUD_RATE = 9600 
838
    valid_freq = [(400000000, 490000000)]
(12-12/14)