Project

General

Profile

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

David Fannin, 05/02/2015 01:08 PM

View differences:

/dev/null Thu Jan 01 00:00:00 1970 +0000 → chirp/drivers/th9000.py Sat May 02 13:01:55 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
#  Note: Features not working:
40
#         - DCS , Cross Signaling
41
#         - Skip channels
42
#
43
# Global Parameters 
44
#
45
MMAPSIZE = 16384
46
TONES = [62.5] + list(chirp_common.TONES)
47
TMODES =  ['','Tone','DTCS'] 
48
DUPLEXES = ['','err','-','+'] # index 2 not used
49
MODES = ['WFM','FM','NFM']  #  25k, 20k,15k bw 
50
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
51
POWER_LEVELS=[chirp_common.PowerLevel("High", watts=65),
52
              chirp_common.PowerLevel("Mid", watts=25),
53
              chirp_common.PowerLevel("Low", watts=10)]
54

  
55
CROSS_MODES = chirp_common.CROSS_MODES
56

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

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

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

  
132
struct {
133
   u8 unknown0100[7];
134
} ropt0100;
135

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

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

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

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

  
358

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

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

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

  
379

  
380

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

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

  
431

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

  
440
def do_download(radio):
441

  
442
    _ident(radio)
443

  
444
    _memobj = None
445
    data = ""
446

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

  
457
    _finish(radio)
458

  
459
    return memmap.MemoryMap(data)
460

  
461
def do_upload(radio):
462

  
463
    _ident(radio)
464

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

  
477
    _finish(radio)
478
            
479

  
480

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

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

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

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

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

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

  
531
    def process_mmap(self):
532
        self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
533

  
534

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

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

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

  
552

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

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

  
565
        mem = chirp_common.Memory()
566

  
567
        mem.number = number  # Set the memory number
568

  
569
        if setflag == 1:
570
            mem.empty = True
571
            return mem
572

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

  
580
        rxtone = txtone = None
581

  
582

  
583
        rxmode = TMODES[_mem.rxtmode]
584
        txmode = TMODES[_mem.txtmode]
585

  
586

  
587
        rxpol = txpol =  ""
588

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

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

  
604

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

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

  
611

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

  
616
        return mem
617

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

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

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

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

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

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

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

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

  
644

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

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

  
653
        _mem.txtmode = TMODES.index(txmode)
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 == "N"
667
        #_mem.rxinv = rxpol == "N"
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)]
(11-11/14)