Project

General

Profile

New Model #1469 » ftm400.py

driver for ftm400 - John Murphy, 09/24/2016 08:18 PM

 
1
# Copybottom 2013 Dan Smith <dsmith@danplanet.com>
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 3 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 time
17
import struct
18
import os
19
import logging
20

    
21
from chirp.drivers import yaesu_clone
22
from chirp import chirp_common, directory, errors, util, bitwise, memmap
23
from chirp.settings import RadioSettingGroup, RadioSetting, RadioSettings
24
from chirp.settings import RadioSettingValueInteger, RadioSettingValueString
25

    
26
LOG = logging.getLogger(__name__)
27

    
28
mem_format = """
29
struct mem {
30
  u8 used:1,
31
     skip:2,
32
     unknown1:5;
33
  u8 unknown2:1,
34
     mode:3,
35
     unknown8:1,
36
     oddsplit:1,
37
     duplex:2;
38
  bbcd freq[3];
39
  u8 unknownA:1,
40
     tmode:3,
41
     unknownB:4;
42
  bbcd split[3];
43
  u8 power:2,
44
     tone:6;
45
  u8 unknownC:1,
46
     dtcs:7;
47
  u8 showalpha:1,
48
     unknown5:7;
49
  u8 unknown6;
50
  u8 offset;
51
  u8 unknown7[2];
52
};
53

    
54
struct lab {
55
  u8 string[8];
56
};
57

    
58
#seekto 0x0508;
59
struct {
60
  char call[6];
61
  u8 ssid;
62
} aprs_my_callsign;
63

    
64
#seekto 0x00b0;
65
struct mem top_memory_zero;
66
#seekto 0x01b0;
67
struct lab top_label_zero;
68
#seekto 0x02b0;
69
struct mem bottom_memory_zero;
70
#seekto 0x03b0;
71
struct lab bottom_label_zero;
72

    
73
#seekto 0x0200;
74
struct mem top_memory[500];
75

    
76
#seekto 0x2260;
77
struct mem bottom_memory[500];
78

    
79
#seekto 0x42C0;
80
struct lab top_label[518];
81
struct lab bottom_label[518];
82
"""
83

    
84
_TMODES = ["", "Tone", "TSQL", "-RVT", "DTCS", "-PR", "-PAG"]
85
TMODES = ["", "Tone", "TSQL", "", "DTCS", "", ""]
86
MODES = ["FM", "AM", "NFM", "", "WFM"]
87
DUPLEXES = ["", "", "-", "+", "split"]
88
# TODO: add japaneese characters (viewable in special menu, scroll backwards)
89
CHARSET = \
90
    ('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!"' +
91
     '#$%&`()*+,-./:;<=>?@[\\]^_`{|}~?????? ' + '?' * 91)
92

    
93
POWER_LEVELS = [chirp_common.PowerLevel("Hi", watts=50),
94
                chirp_common.PowerLevel("Mid", watts=20),
95
                chirp_common.PowerLevel("Low", watts=5)]
96

    
97
SKIPS = ["", "S", "P"]
98

    
99

    
100
def aprs_call_to_str(_call):
101
    call = ""
102
    for i in str(_call):
103
        if i == "\xca":
104
            break
105
        call += i
106
    return call
107

    
108

    
109
def _safe_read(radio, length):
110
    data = ""
111
    while len(data) < length:
112
        data += radio.pipe.read(length - len(data))
113
    return data
114

    
115

    
116
def _clone_in(radio):
117
    data = ""
118

    
119
    radio.pipe.timeout = 1
120
    attempts = 30
121

    
122
    data = memmap.MemoryMap("\x00" * (radio._memsize + 128))
123
    length = 0
124
    last_addr = 0
125
    while length < radio._memsize:
126
        frame = radio.pipe.read(131)
127
        if length and not frame:
128
            raise errors.RadioError("Radio not responding")
129

    
130
        if not frame:
131
            attempts -= 1
132
            if attempts <= 0:
133
                raise errors.RadioError("Radio not responding")
134

    
135
        if frame:
136
            addr, = struct.unpack(">H", frame[0:2])
137
            checksum = ord(frame[130])
138
            block = frame[2:130]
139

    
140
            cs = 0
141
            for i in frame[:-1]:
142
                cs = (cs + ord(i)) % 256
143
            if cs != checksum:
144
                LOG.debug("Calc: %02x Real: %02x Len: %i" %
145
                          (cs, checksum, len(block)))
146
                raise errors.RadioError("Block failed checksum")
147

    
148
            radio.pipe.write("\x06")
149
            time.sleep(0.05)
150

    
151
            if (last_addr + 128) != addr:
152
                LOG.debug("Gap, expecting %04x, got %04x" %
153
                          (last_addr+128, addr))
154
            last_addr = addr
155
            data[addr] = block
156
            length += len(block)
157

    
158
        status = chirp_common.Status()
159
        status.cur = length
160
        status.max = radio._memsize
161
        status.msg = "Cloning from radio"
162
        radio.status_fn(status)
163

    
164
    return data
165

    
166

    
167
def _clone_out(radio):
168
    radio.pipe.timeout = 1
169

    
170
    # Seriously, WTF Yaesu?
171
    ranges = [
172
        (0x0000, 0x0000),
173
        (0x0100, 0x0380),
174
        (0x0480, 0xFF80),
175
        (0x0080, 0x0080),
176
        (0xFFFE, 0xFFFE),
177
        ]
178

    
179
    for start, end in ranges:
180
        for i in range(start, end+1, 128):
181
            block = radio._mmap[i:i + 128]
182
            frame = struct.pack(">H", i) + block
183
            cs = 0
184
            for byte in frame:
185
                cs += ord(byte)
186
            frame += chr(cs % 256)
187
            radio.pipe.write(frame)
188
            ack = radio.pipe.read(1)
189
            if ack != "\x06":
190
                raise errors.RadioError("Radio refused block %i" % (i / 128))
191
            time.sleep(0.05)
192

    
193
            status = chirp_common.Status()
194
            status.cur = i + 128
195
            status.max = radio._memsize
196
            status.msg = "Cloning to radio"
197
            radio.status_fn(status)
198

    
199

    
200
def get_freq(rawfreq):
201
    """Decode a frequency that may include a fractional step flag"""
202
    # Ugh.  The 0x80 and 0x40 indicate values to add to get the
203
    # real frequency.  Gross.
204
    if rawfreq > 8000000000:
205
        rawfreq = (rawfreq - 8000000000) + 5000
206

    
207
    if rawfreq > 4000000000:
208
        rawfreq = (rawfreq - 4000000000) + 2500
209

    
210
    if rawfreq > 2000000000:
211
        rawfreq = (rawfreq - 2000000000) + 1250
212

    
213
    return rawfreq
214

    
215

    
216
def set_freq(freq, obj, field):
217
    """Encode a frequency with any necessary fractional step flags"""
218
    obj[field] = freq / 10000
219
    frac = freq % 10000
220

    
221
    if frac >= 5000:
222
        frac -= 5000
223
        obj[field][0].set_bits(0x80)
224

    
225
    if frac >= 2500:
226
        frac -= 2500
227
        obj[field][0].set_bits(0x40)
228

    
229
    if frac >= 1250:
230
        frac -= 1250
231
        obj[field][0].set_bits(0x20)
232

    
233
    return freq
234

    
235

    
236
@directory.register
237
class FTM400Radio(yaesu_clone.YaesuCloneModeRadio):
238
    """Yaesu FTM-400"""
239
    BAUD_RATE = 48000
240
    VENDOR = "Yaesu"
241
    MODEL = "FTM-400"
242

    
243
    _model = ""
244
    _memsize = 65536
245
    _vfo = ""
246

    
247
    def get_features(self):
248
        rf = chirp_common.RadioFeatures()
249
        rf.has_bank = False
250
        rf.has_ctone = False
251
        rf.has_settings = self._vfo == "top"
252
        rf.has_tuning_step = False
253
        rf.has_dtcs_polarity = False
254
        rf.has_sub_devices = self.VARIANT == ""
255
        rf.valid_skips = []  # FIXME: Finish this
256
        rf.valid_tmodes = [""] + [x for x in TMODES if x]
257
        rf.valid_modes = [x for x in MODES if x]
258
        rf.valid_duplexes = DUPLEXES
259
        rf.valid_skips = SKIPS
260
        rf.valid_name_length = 8
261
        rf.valid_characters = CHARSET
262
        rf.memory_bounds = (0, 500)
263
        rf.valid_power_levels = POWER_LEVELS
264
        rf.valid_bands = [(500000,   1800000),
265
                          (76000000, 250000000),
266
                          (30000000, 1000000000)]
267
        rf.can_odd_split = True
268
        return rf
269

    
270
    def get_sub_devices(self):
271
        return [FTM400RadioTop(self._mmap), FTM400RadioBottom(self._mmap)]
272

    
273
    def sync_in(self):
274
        try:
275
            self._mmap = _clone_in(self)
276
        except errors.RadioError:
277
            raise
278
        except Exception, e:
279
            raise errors.RadioError("Failed to download from radio (%s)" % e)
280
        self.process_mmap()
281

    
282
    def sync_out(self):
283
        try:
284
            _clone_out(self)
285
        except errors.RadioError:
286
            raise
287
        except Exception, e:
288
            raise errors.RadioError("Failed to upload to radio (%s)" % e)
289

    
290
    def process_mmap(self):
291
        self._memobj = bitwise.parse(mem_format, self._mmap)
292

    
293
    def get_raw_memory(self, number):
294

    
295
        def identity(o):
296
            return o
297

    
298
        def indexed(o):
299
            return o[number - 1]
300

    
301
        if number == 0:
302
            suffix = "_zero"
303
            fn = identity
304
        else:
305
            suffix = ""
306
            fn = indexed
307
        return (repr(fn(self._memory_obj(suffix))) +
308
                repr(fn(self._label_obj(suffix))))
309

    
310
    def _memory_obj(self, suffix=""):
311
        return getattr(self._memobj, "%s_memory%s" % (self._vfo, suffix))
312

    
313
    def _label_obj(self, suffix=""):
314
        return getattr(self._memobj, "%s_label%s" % (self._vfo, suffix))
315

    
316
    def get_memory(self, number):
317
        if number == 0:
318
            _mem = self._memory_obj("_zero")
319
            _lab = self._label_obj("_zero")
320
        else:
321
            _mem = self._memory_obj()[number - 1]
322
            _lab = self._label_obj()[number - 1]
323
        mem = chirp_common.Memory()
324
        mem.number = number
325

    
326
        if not _mem.used:
327
            mem.empty = True
328
            return mem
329

    
330
        mem.freq = get_freq(int(_mem.freq) * 10000)
331
        mem.rtone = chirp_common.TONES[_mem.tone]
332
        mem.tmode = TMODES[_mem.tmode]
333

    
334
        if _mem.oddsplit:
335
            mem.duplex = "split"
336
            mem.offset = get_freq(int(_mem.split) * 10000)
337
        else:
338
            mem.duplex = DUPLEXES[_mem.duplex]
339
            mem.offset = int(_mem.offset) * 50000
340

    
341
        mem.dtcs = chirp_common.DTCS_CODES[_mem.dtcs]
342
        mem.mode = MODES[_mem.mode]
343
        mem.skip = SKIPS[_mem.skip]
344
        mem.power = POWER_LEVELS[_mem.power]
345

    
346
        for char in _lab.string:
347
            if char == 0xCA:
348
                break
349
            try:
350
                mem.name += CHARSET[char]
351
            except IndexError:
352
                mem.name += "?"
353
        mem.name = mem.name.rstrip()
354

    
355
        return mem
356

    
357
    def set_memory(self, mem):
358
        if mem.number == 0:
359
            _mem = self._memory_obj("_zero")
360
            _lab = self._label_obj("_zero")
361
        else:
362
            _mem = self._memory_obj()[mem.number - 1]
363
            _lab = self._label_obj()[mem.number - 1]
364
        _mem.used = not mem.empty
365
        if mem.empty:
366
            return
367

    
368
        set_freq(mem.freq, _mem, 'freq')
369
        _mem.tone = chirp_common.TONES.index(mem.rtone)
370
        _mem.dtcs = chirp_common.DTCS_CODES.index(mem.dtcs)
371
        _mem.tmode = TMODES.index(mem.tmode)
372
        _mem.mode = MODES.index(mem.mode)
373
        _mem.skip = SKIPS.index(mem.skip)
374

    
375
        _mem.oddsplit = 0
376
        _mem.duplex = 0
377
        if mem.duplex == "split":
378
            set_freq(mem.offset, _mem, 'split')
379
            _mem.oddsplit = 1
380
        else:
381
            _mem.offset = mem.offset / 50000
382
            _mem.duplex = DUPLEXES.index(mem.duplex)
383

    
384
        if mem.power:
385
            _mem.power = POWER_LEVELS.index(mem.power)
386
        else:
387
            _mem.power = 0
388

    
389
        for i in range(0, 8):
390
            try:
391
                char = CHARSET.index(mem.name[i])
392
            except IndexError:
393
                char = 0xCA
394
            _lab.string[i] = char
395
        _mem.showalpha = mem.name.strip() != ""
396

    
397
    @classmethod
398
    def match_model(self, filedata, filename):
399
        return filedata.startswith("AH034$")
400

    
401
    def get_settings(self):
402
        top = RadioSettings()
403

    
404
        aprs = RadioSettingGroup("aprs", "APRS")
405
        top.append(aprs)
406

    
407
        myc = self._memobj.aprs_my_callsign
408
        rs = RadioSetting("aprs_my_callsign.call", "APRS My Callsign",
409
                          RadioSettingValueString(0, 6,
410
                                                  aprs_call_to_str(myc.call)))
411
        aprs.append(rs)
412

    
413
        rs = RadioSetting("aprs_my_callsign.ssid", "APRS My SSID",
414
                          RadioSettingValueInteger(0, 15, myc.ssid))
415
        aprs.append(rs)
416

    
417
        return top
418

    
419
    def set_settings(self, settings):
420
        for setting in settings:
421
            if not isinstance(setting, RadioSetting):
422
                self.set_settings(setting)
423
                continue
424

    
425
            # Quick hack to make these work
426
            if setting.get_name() == "aprs_my_callsign.call":
427
                self._memobj.aprs_my_callsign.call = \
428
                    setting.value.get_value().upper().replace(" ", "\xCA")
429
            elif setting.get_name() == "aprs_my_callsign.ssid":
430
                self._memobj.aprs_my_callsign.ssid = setting.value
431

    
432

    
433
class FTM400RadioTop(FTM400Radio):
434
    VARIANT = "Top"
435
    _vfo = "top"
436

    
437

    
438
class FTM400RadioBottom(FTM400Radio):
439
    VARIANT = "Bottom"
440
    _vfo = "bottom"
(6-6/6)