Project

General

Profile

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

David Fannin, 04/27/2015 11:50 PM

View differences:

/dev/null Thu Jan 01 00:00:00 1970 +0000 → chirp/drivers/th9000.py Mon Apr 27 23:40:03 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
@directory.register
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 = chirp_common.TONE_MODES
517
        rf.valid_cross_modes = CROSS_MODES
518
        rf.valid_power_levels = POWER_LEVELS
519
        rf.valid_dtcs_codes = chirp_common.ALL_DTCS_CODES
520
        rf.valid_bands = self.valid_freq
521
        return rf
522

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

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

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

  
535

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

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

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

  
553

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

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

  
566
        mem = chirp_common.Memory()
567

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

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

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

  
581
        rxtone = txtone = None
582

  
583

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

  
587

  
588
        rxpol = txpol =  ""
589

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

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

  
605

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

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

  
612

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

  
617
        return mem
618

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

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

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

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

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

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

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

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

  
645

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

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

  
654
        _mem.txtmode = TMODES.index(txmode)
655
        _mem.rxtmode = TMODES.index(rxmode)
656

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

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

  
667
        #_mem.txinv = txpol == "N"
668
        #_mem.rxinv = rxpol == "N"
669

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  
756
        return settings
757

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

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

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

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

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

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

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

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

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

  
815
        return False
816

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

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

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