Project

General

Profile

Bug #10960 » ftm350.py

1eea558f - Dan Smith, 11/23/2023 07:34 AM

 
1
# Copyright 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 logging
19

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

    
25
LOG = logging.getLogger(__name__)
26

    
27
mem_format = """
28
struct mem {
29
  u8 used:1,
30
     skip:2,
31
     unknown1:4,
32
     visible:1;
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 0x0480;
65
struct mem left_memory_zero;
66
#seekto 0x04A0;
67
struct lab left_label_zero;
68
#seekto 0x04C0;
69
struct mem right_memory_zero;
70
#seekto 0x04E0;
71
struct lab right_label_zero;
72

    
73
#seekto 0x0800;
74
struct mem left_memory[500];
75

    
76
#seekto 0x2860;
77
struct mem right_memory[500];
78

    
79
#seekto 0x48C0;
80
struct lab left_label[518];
81
struct lab right_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", "off"]
88
# TODO: add Japanese 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.MemoryMapBytes(b"\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 = frame[130]
138
            block = frame[2:130]
139

    
140
            cs = 0
141
            for i in frame[:-1]:
142
                cs = (cs + 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(b"\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 += byte
186
            frame += bytes([cs % 256])
187
            radio.pipe.write(frame)
188
            ack = radio.pipe.read(1)
189
            if ack != b"\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 FTM350Radio(yaesu_clone.YaesuCloneModeRadio):
238
    """Yaesu FTM-350"""
239
    BAUD_RATE = 48000
240
    VENDOR = "Yaesu"
241
    MODEL = "FTM-350"
242
    NEEDS_COMPAT_SERIAL = False
243

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

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

    
272
        return rf
273

    
274
    def get_sub_devices(self):
275
        return [FTM350RadioLeft(self._mmap), FTM350RadioRight(self._mmap)]
276

    
277
    def sync_in(self):
278
        try:
279
            self._mmap = _clone_in(self)
280
        except errors.RadioError:
281
            raise
282
        except Exception as e:
283
            LOG.exception('Failed to read: %s', e)
284
            raise errors.RadioError("Failed to download from radio (%s)" % e)
285
        self.process_mmap()
286

    
287
    def sync_out(self):
288
        try:
289
            _clone_out(self)
290
        except errors.RadioError:
291
            raise
292
        except Exception as e:
293
            LOG.exception('Failed to write: %s', e)
294
            raise errors.RadioError("Failed to upload to radio (%s)" % e)
295

    
296
    def process_mmap(self):
297
        self._memobj = bitwise.parse(mem_format, self._mmap)
298

    
299
    def get_raw_memory(self, number):
300

    
301
        def identity(o):
302
            return o
303

    
304
        def indexed(o):
305
            return o[number - 1]
306

    
307
        if number == 0:
308
            suffix = "_zero"
309
            fn = identity
310
        else:
311
            suffix = ""
312
            fn = indexed
313
        return (repr(fn(self._memory_obj(suffix))) +
314
                repr(fn(self._label_obj(suffix))))
315

    
316
    def _memory_obj(self, suffix=""):
317
        return getattr(self._memobj, "%s_memory%s" % (self._vfo, suffix))
318

    
319
    def _label_obj(self, suffix=""):
320
        return getattr(self._memobj, "%s_label%s" % (self._vfo, suffix))
321

    
322
    def get_memory(self, number):
323
        if number == 0:
324
            _mem = self._memory_obj("_zero")
325
            _lab = self._label_obj("_zero")
326
        else:
327
            _mem = self._memory_obj()[number - 1]
328
            _lab = self._label_obj()[number - 1]
329
        mem = chirp_common.Memory()
330
        mem.number = number
331

    
332
        if not _mem.used:
333
            mem.empty = True
334
            return mem
335

    
336
        if _mem.offset == 0xFF:
337
            # TX disabled
338
            mem.duplex = "off"
339
        elif _mem.oddsplit:
340
            mem.duplex = "split"
341
            mem.offset = get_freq(int(_mem.split) * 10000)
342
        else:
343
            mem.duplex = DUPLEXES[_mem.duplex]
344
            mem.offset = int(_mem.offset) * 50000
345

    
346
        mem.freq = get_freq(int(_mem.freq) * 10000)
347
        if mem.duplex != "off":
348
            mem.rtone = chirp_common.TONES[_mem.tone]
349
            mem.dtcs = chirp_common.DTCS_CODES[_mem.dtcs]
350
            mem.power = POWER_LEVELS[_mem.power]
351
            mem.tmode = TMODES[_mem.tmode]
352

    
353
        mem.mode = MODES[_mem.mode]
354
        mem.skip = SKIPS[_mem.skip]
355

    
356
        for char in _lab.string:
357
            if char == 0xCA:
358
                break
359
            try:
360
                mem.name += CHARSET[char]
361
            except IndexError:
362
                mem.name += "?"
363
        mem.name = mem.name.rstrip()
364

    
365
        return mem
366

    
367
    def set_memory(self, mem):
368
        if mem.number == 0:
369
            _mem = self._memory_obj("_zero")
370
            _lab = self._label_obj("_zero")
371
        else:
372
            _mem = self._memory_obj()[mem.number - 1]
373
            _lab = self._label_obj()[mem.number - 1]
374
        _mem.used = not mem.empty
375
        _mem.visible = not mem.empty
376
        if mem.empty:
377
            return
378

    
379
        set_freq(mem.freq, _mem, 'freq')
380

    
381
        _mem.oddsplit = 0
382
        _mem.tone = chirp_common.TONES.index(mem.rtone)
383
        _mem.dtcs = chirp_common.DTCS_CODES.index(mem.dtcs)
384
        _mem.tmode = TMODES.index(mem.tmode)
385
        _mem.duplex = DUPLEXES.index(mem.duplex)
386
        if mem.duplex == "off":
387
            _mem.tone = 0x3F
388
            _mem.dtcs = 0x7F
389
            _mem.offset = 0xFF
390
            _mem.power = 0x03
391
            _mem.tmode = 0x00
392
            _mem.duplex = 0x00
393
        elif mem.duplex == "split":
394
            set_freq(mem.offset, _mem, 'split')
395
            _mem.oddsplit = 1
396
        else:
397
            _mem.offset = mem.offset / 50000
398

    
399
        _mem.mode = MODES.index(mem.mode)
400
        _mem.skip = SKIPS.index(mem.skip)
401

    
402
        if mem.power:
403
            _mem.power = POWER_LEVELS.index(mem.power)
404
        else:
405
            _mem.power = 0
406

    
407
        for i in range(0, 8):
408
            try:
409
                char = CHARSET.index(mem.name[i])
410
            except IndexError:
411
                char = 0xCA
412
            _lab.string[i] = char
413
        _mem.showalpha = mem.name.strip() != ""
414

    
415
    @classmethod
416
    def match_model(self, filedata, filename):
417
        return filedata.startswith(b"AH033$")
418

    
419
    def get_settings(self):
420
        top = RadioSettings()
421

    
422
        aprs = RadioSettingGroup("aprs", "APRS")
423
        top.append(aprs)
424

    
425
        myc = self._memobj.aprs_my_callsign
426
        rs = RadioSetting("aprs_my_callsign.call", "APRS My Callsign",
427
                          RadioSettingValueString(0, 6,
428
                                                  aprs_call_to_str(myc.call)))
429
        aprs.append(rs)
430

    
431
        rs = RadioSetting("aprs_my_callsign.ssid", "APRS My SSID",
432
                          RadioSettingValueInteger(0, 15, myc.ssid))
433
        aprs.append(rs)
434

    
435
        return top
436

    
437
    def set_settings(self, settings):
438
        for setting in settings:
439
            if not isinstance(setting, RadioSetting):
440
                self.set_settings(setting)
441
                continue
442

    
443
            # Quick hack to make these work
444
            if setting.get_name() == "aprs_my_callsign.call":
445
                self._memobj.aprs_my_callsign.call = \
446
                    setting.value.get_value().upper().replace(" ", "\xCA")
447
            elif setting.get_name() == "aprs_my_callsign.ssid":
448
                self._memobj.aprs_my_callsign.ssid = setting.value
449

    
450

    
451
class FTM350RadioLeft(FTM350Radio):
452
    VARIANT = "Left"
453
    _vfo = "left"
454

    
455

    
456
class FTM350RadioRight(FTM350Radio):
457
    VARIANT = "Right"
458
    _vfo = "right"
(2-2/2)