Project

General

Profile

Bug #10304 » icx90.py

Dan Smith, 01/23/2023 08:40 PM

 
1
# -*- coding: utf-8 -*-
2
# Copyright 2018-2020 Jaroslav Škarvada <jskarvad@redhat.com>
3
# Based on various code from the CHIRP
4

    
5
# This program is free software: you can redistribute it and/or modify
6
# it under the terms of the GNU General Public License as published by
7
# the Free Software Foundation, either version 3 of the License, or
8
# (at your option) any later version.
9
#
10
# This program is distributed in the hope that it will be useful,
11
# but WITHOUT ANY WARRANTY; without even the implied warranty of
12
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
# GNU General Public License for more details.
14
#
15
# You should have received a copy of the GNU General Public License
16
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
17

    
18
import logging
19

    
20
from chirp.drivers import icf
21
import struct
22
from chirp import chirp_common, bitwise, errors, directory
23
from chirp.memmap import MemoryMap
24
from chirp.settings import RadioSetting, RadioSettingGroup, \
25
    RadioSettingValueInteger, RadioSettingValueList, \
26
    RadioSettingValueBoolean, RadioSettingValueString, \
27
    RadioSettingValueFloat, InvalidValueError, RadioSettings
28
import argparse
29

    
30
ICX90_MEM_FORMAT = """
31
struct mem_item {
32
  ul24 freq;
33
  u8 dtcs_polarity:2,
34
     unknown_1:2,
35
     offset_freq_mult:1,
36
     unknown_2:2,
37
     freq_mult:1;
38
  u8 unknown_3:1,
39
     duplex:2,
40
     mode:2,
41
     tone_mode:3;
42
  ul16 offset_freq;
43
  u8 dtcs;
44
  u8 tx_tone_lo:4,
45
     tune_step:4;
46
  u8 rx_tone:6,
47
     tx_tone_hi:2;
48
  char name[6];
49
};
50
struct bank_item {
51
  u8 invisible_channel:1,
52
     prog_skip:1,
53
     mem_skip:1,
54
     bank_index:5;
55
  u8 bank_channel;
56
};
57
struct tv_mem_item {
58
  u8 fixed:7,
59
     mode:1;
60
  ul24 freq;
61
  char name[4];
62
};
63

    
64
struct mem_item memory[500];
65
struct mem_item scan_edges[50];
66
struct bank_item banks[500];
67
u8 unknown_4[120];
68
struct mem_item vfo_a_band[10];
69
struct mem_item vfo_b_band[10];
70
struct mem_item call_channels[5];
71
struct tv_mem_item tv_memory[68];
72
u8 unknown_5[35];
73
ul16 mem_channel;
74
u8 autodial;
75
u8 unknown_6[8];
76
u8 unknown_7:6,
77
   skip_scan:1,
78
   unknown_8:1;
79
u8 squelch_level;
80
struct {
81
  char dtmf_digits[16];
82
} dtmf_codes[10];
83
u8 tv_channel_skip[68];
84
u8 unknown_9[128];
85
u8 scan_resume;
86
u8 scan_pause;
87
u8 unknown_10;
88
u8 beep_volume;
89
u8 beep;
90
u8 backlight;
91
u8 busy_led;
92
u8 auto_power_off;
93
u8 power_save;
94
u8 monitor;
95
u8 dial_speedup;
96
u8 unknown_11;
97
u8 auto_repeater;
98
u8 dtmf_speed;
99
u8 hm_75a_function;
100
u8 wx_alert;
101
u8 expand_1;
102
u8 scan_stop_beep;
103
u8 scan_stop_light;
104
u8 unknown_12;
105
u8 light_position;
106
u8 light_color;
107
u8 unknown_13;
108
u8 band_edge_beep;
109
u8 auto_power_on;
110
u8 key_lock;
111
u8 ptt_lock;
112
u8 lcd_contrast;
113
u8 opening_message;
114
u8 expand_2;
115
u8 unknown_14;
116
u8 busy_lockout;
117
u8 timeout_timer;
118
u8 active_band;
119
u8 split;
120
u8 fm_narrow;
121
u8 morse_code_enable;
122
u8 morse_code_speed;
123
u8 unknown_15[22];
124
char opening_message_text[6];
125
u8 unknown_16[186];
126
u8 unknown_17:4,
127
   tune_step:4;
128
u8 unknown_18[4];
129
u8 band_selected;
130
u8 unknown_19[2];
131
u8 unknown_20:2,
132
   attenuator:1,
133
   vfo:1,
134
   power:1,
135
   dial_select:1,
136
   memory_name:1,
137
   memory_display:1;
138
u8 unknown_21[2];
139
u8 mode:4,
140
   unknown_22:4;
141
u8 unknown_23[9];
142
char alpha_tag[6];
143
u8 vfo_scan;
144
u8 memory_scan;
145
u8 unknown_24;
146
u8 tv_channel;
147
u8 wx_channel;
148
char comment[16];
149
"""
150

    
151
LOG = logging.getLogger(__name__)
152

    
153
# in bytes
154
MEM_ITEM_SIZE = 16
155
TV_MEM_ITEM_SIZE = 8
156

    
157
BANK_INDEX = ["A", "B", "C", "D", "E", "F", "G", "H", "J", "L", "N", "O",
158
              "P", "Q", "R", "T", "U", "Y"]
159
MEM_NUM = 500
160
BANKS = 18
161
BANK_NUM = 100
162
BANK_INDEX_NUM = len(BANK_INDEX)
163
DTMF_AUTODIAL_NUM = 10
164
DTMF_DIGITS_NUM = 16
165
OPENING_MESSAGE_LEN = 6
166
COMMENT_LEN = 16
167
BANDS=10
168
TV_CHANNELS=68
169

    
170
CHARSET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789()*+-,/|= "
171
NAME_LENGTH = 6
172
TV_NAME_LENGTH = 4
173
DUPLEX = ["", "-", "+", ""]
174
DTCS_POLARITY = ["NN", "NR", "RN", "RR"]
175
TONE_MODE = ["", "Tone", "TSQL", "DTCS"]
176
TUNE_STEP = [5.0, 6.25, 8.33, 9.0, 10.0, 12.5, 15.0, 20.0, 25.0, 30.0, 50.0, 100.0, 200.0]
177
TUNE_STEP_STR = [str(x) for x in TUNE_STEP]
178
MODE = ["FM", "WFM", "AM"]
179
TV_MODE = ["WFM", "AM"]
180

    
181
SQUELCH_LEVEL = ["Open", "Auto", "Level 1", "Level 2", "Level 3", "Level 4", "Level 5",
182
                 "Level 6", "Level 7", "Level 8", "Level 9"]
183
AUTODIAL = ["Tone call", "D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9"]
184
DTMF_SPEED = ["100 ms", "200 ms", "300 ms", "400 ms"]
185
SCAN_RESUME = ["0 s", "1 s", "2 s", "3 s", "4 s", "5 s", "Hold"]
186
SCAN_PAUSE = ["2 s", "4 s", "6 s", "8 s", "10 s", "12 s", "14 s", "16 s", "18 s", "20 s", "Hold"]
187
BEEP_VOLUME = ["Volume", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12",
188
               "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25",
189
               "26", "27", "28", "29", "30", "31"]
190
BACKLIGHT = ["Off", "On", "Auto"]
191
AUTO_POWER_OFF = ["Off", "30 min", "60 min", "90 min", "120 min"]
192
POWER_SAVE = ["Off", "1:1", "1:4", "1:8", "1:16", "Auto"]
193
MONITOR = ["Push", "Hold"]
194
AUTO_REPEATER = ["Off", "Duplex only", "Duplex & tone"]
195
HM_75A_FUNCTION = ["Simple", "Normal 1", "Normal 2"]
196
LIGHT_POSITION = ["LCD", "Key", "All"]
197
LIGHT_COLOR = ["Green", "Orange", "Red"]
198
AUTO_POWER_ON = ["Off", "00:30", "01:00", "01:30", "02:00", "02:30", "03:00", "03:30", "04:00",
199
                 "04:30", "05:00", "05:30", "06:00", "06:30", "07:00", "07:30", "08:00",
200
                 "08:30", "09:00", "09:30", "10:00", "10:30", "11:00", "11:30", "12:00",
201
                 "12:30", "13:00", "13:30", "14:00", "14:30", "15:00", "15:30", "16:00",
202
                 "16:30", "17:00", "17:30", "18:00", "18:30", "19:00", "19:30", "20:00",
203
                 "20:30", "21:00", "21:30", "22:00", "22:30", "23:00", "23:30", "24:00"]
204
KEY_LOCK = ["Normal", "No squelch", "No volume", "All"]
205
LCD_CONTRAST = ["1", "2", "3", "4"]
206
TIMEOUT_TIMER = ["Off", "1 min", "3 min", "5 min", "10 min"]
207
ACTIVE_BAND = ["All", "Single"]
208
MORSE_CODE_SPEED = ["10 WPM", "15 WPM", "20 WPM", "25 WPM"]
209
WX_CHANNEL = ["WX01", "WX02", "WX03", "WX04", "WX05", "WX06", "WX07", "WX08", "WX09", "WX10"]
210
MEMORY_DISPLAY = ["Channel", "Bank"]
211
DIAL_SELECT = ["Normal", "Volume"]
212
POWER = ["High", "Low"]
213
VFO = ["A", "B"]
214
OPERATION_MODE = ["VFO", "Memory", "Call channel", "TV"]
215
VFO_SCAN = ["All", "Band", "P0", "P1", "P2", "P3", "P4", "P5", "P6", "P7", "P8",
216
            "P9", "P10", "P11", "P12", "P13", "P14", "P15", "P16", "P17", "P18",
217
            "P19", "P20", "P21", "P22", "P23", "P24"]
218
MEMORY_SCAN = ["All", "Bank", "Sel BC", "Sel 5 MHz", "Sel 50 MHz", "Sel WFM", "Sel Air",
219
               "Sel 144 MHz", "Sel 220 MHz", "Sel 300 MHz", "Sel 440 MHz", "Sel 800 MHz"]
220

    
221
class ICx90BankModel(icf.IcomIndexedBankModel):
222
    bank_index = BANK_INDEX
223

    
224
    def get_mappings(self):
225
        banks = []
226

    
227
        if (self._radio._num_banks != len(type(self).bank_index)):
228
            raise Exception("Invalid number of banks %d, supported only %d banks" %
229
                (self._radio._num_banks, len(type(self).bank_index)))
230

    
231
        for i in range(0, self._radio._num_banks):
232
            index = type(self).bank_index[i]
233
            bank = self._radio._bank_class(self, index, "BANK-%s" % index)
234
            bank.index = i
235
            banks.append(bank)
236

    
237
        return banks
238

    
239
class ICT90_Alias(chirp_common.Alias):
240
    VENDOR = "Icom"
241
    MODEL = "IC-T90"
242

    
243
@directory.register
244
class ICx90Radio(icf.IcomCloneModeRadio):
245
    """Icom IC-E/T90"""
246
    VENDOR = "Icom"
247
    MODEL = "IC-E90"
248
    # read clone response after each clone frame is sent
249
    # MUNCH_CLONE_RESP = True
250

    
251
    ALIASES = [ICT90_Alias]
252

    
253
    _model = "\x25\x07\x00\x01"
254
    _memsize = 0x2d40
255
    _endframe = "Icom Inc."
256

    
257
    _ranges = [(0x0000, 0x2d40, 32)]
258
    _num_banks = BANKS
259
    _bank_index_bounds = (0, BANK_NUM - 1)
260
    _can_hispeed = False
261

    
262
    def __init__(self, pipe):
263
        icf.IcomCloneModeRadio.__init__(self, pipe)
264

    
265
    def special_add(self, key, item_type, num, unique_idx):
266
          item = {}
267
          item["item_type"] = item_type
268
          item["num"] = num
269
          item["uidx"] = unique_idx
270
          self.special[key] = item
271

    
272
    def init_special(self):
273
      self.special = {}
274
      i = 0
275
      # program scan edges
276
      for x in range(25):
277
          self.special_add("Scan edge: %02dA" % x, "scan_edge", x * 2, i)
278
          self.special_add("Scan edge: %02dB" % x, "scan_edge", x * 2 + 1, i + 1)
279
          i += 2
280
      # call channels
281
      for x in range(5):
282
          self.special_add("Call ch: %d" % x, "call_chan", x, i)
283
          i += 1
284
      # VFO A
285
      for x in range(10):
286
          self.special_add("VFO A: %d" % x, "vfo_a", x, i)
287
          i += 1
288
      # VFO B
289
      for x in range(10):
290
          self.special_add("VFO B: %d" % x, "vfo_b", x, i)
291
          i += 1
292

    
293
    def get_sub_devices(self):
294
        return [ICx90Radio_ham(self._mmap), ICx90Radio_tv(self._mmap)]
295

    
296
    def clear_bank(self, loc):
297
        # it seems that empty invisible channel which isn't in bank is defined in bank_item by bytes 0x9f 0x00,
298
        # i.e. it has invisible_channel == 1
299
        # it seems that non-empty visible channel which isn't in bank is defined in bank_item by bytes 0x1f 0x00,
300
        # i.e. it has invisible_channel == 0
301
        # so do not touch the invisible_channel (the bit 7 of the first byte) here and only
302
        # set the rest of the bits
303
        self.memobj.banks[loc].bank_index = 0x1f
304
        self.memobj.banks[loc].prog_skip = 0
305
        self.memobj.banks[loc].mem_skip = 0
306
        self.memobj.banks[loc].bank_channel = 0
307

    
308
    # it seems the bank driver has different terminology about bank number and index
309
    # so in fact _get_bank and _set_bank are about indexes (i.e index in the array
310
    # of bank names - A .. Y
311
    # and _get_bank_index and _set_bank_index are about positions in the bank (0..99)
312
    def _get_bank(self, loc):
313
        i = self.memobj.banks[loc].bank_index
314
        return i if i < BANK_INDEX_NUM else None
315

    
316
    def _set_bank(self, loc, bank):
317
        if bank is None:
318
            self.clear_bank(loc)
319
        else:
320
            self.memobj.banks[loc].bank_index = bank
321
            # it seems if invisible_channel == 1 the channel is invisible (deleted)
322
            # so set it explicitly as visible
323
            self.memobj.banks[loc].invisible_channel = 0
324

    
325
    def _get_bank_index(self, loc):
326
        i = self.memobj.banks[loc].bank_channel
327
        return i if i < BANK_NUM else None
328

    
329
    def _set_bank_index(self, loc, index):
330
        self.memobj.banks[loc].bank_channel = index
331

    
332
    def get_features(self):
333
        self.init_special()
334
        rf = chirp_common.RadioFeatures()
335
        rf.has_settings = True
336
        rf.has_name = True
337
        rf.has_bank = True
338
        rf.has_bank_index = True
339
        rf.has_bank_names = False
340
        rf.can_delete = True
341
        rf.has_ctone = True
342
        rf.has_dtcs = True
343
        rf.has_dtcs_polarity = True
344
        rf.has_tuning_step = True
345
        rf.has_comment = False
346
        rf.memory_bounds = (0, MEM_NUM - 1)
347
        rf.has_sub_devices = True
348
        rf.valid_characters = CHARSET
349
        rf.valid_modes = list(MODE)
350
        rf.valid_tmodes = list(TONE_MODE)
351
        rf.valid_duplexes = list(DUPLEX)[:-1]
352
        rf.valid_tuning_steps = list(TUNE_STEP)
353
        rf.valid_bands = [(495000, 999990000)]
354
        rf.valid_skips = ["", "S", "P"]
355
        rf.valid_name_length = NAME_LENGTH
356
        rf.valid_special_chans = sorted(self.special.keys())
357

    
358
        return rf
359

    
360
    def map_dtmf_chirp2icom(self, item):
361
        item = str(item).upper()
362
        if item == "*":
363
            item = "E"
364
        elif item == "#":
365
            item = "F"
366
        elif item == " ":
367
            return 0xff
368
        try:
369
            ret = int(item, 16)
370
        except ValueError:
371
            raise errors.InvalidDataError("invalid DTMF number '%s'" % item)
372
        return ret
373

    
374
    def dtmf_chirp2icom(self, dtmf):
375
        return "".join(map(self.map_dtmf_chirp2icom, str(dtmf).rjust(DTMF_DIGITS_NUM)))
376

    
377
    def map_dtmf_icom2chirp(self, item):
378
        item = ord(item)
379
        if item == 0xff:
380
            return " "
381
        else:
382
            item &= 0x0f
383
            if item < 10:
384
                return str(item)
385
            else:
386
                return ["A", "B", "C", "D", "*", "#"][item - 10]
387

    
388
    def dtmf_icom2chirp(self, dtmf):
389
        return "".join(map(self.map_dtmf_icom2chirp, str(dtmf)))
390

    
391
    def apply_dtmf_autodial(self, setting, obj):
392
        obj = self.dtmf_chirp2icom(setting.value)
393

    
394
    def get_settings(self):
395
        try:
396
            _squelch = 1
397
            basic = RadioSettingGroup("basic", "Basic")
398
            expand_1 = RadioSettingGroup("expand_1", "Expand 1")
399
            expand_2 = RadioSettingGroup("expand_2", "Expand 2")
400
            dtmf_autodial = RadioSettingGroup("dtmf_autodial", "DTMF autodial")
401
            group = RadioSettings(basic, expand_1, expand_2, dtmf_autodial)
402

    
403
            # basic
404
            basic.append(RadioSetting("mem_channel", "Current memory channel",
405
                         RadioSettingValueInteger(0, MEM_NUM - 1, self.memobj.mem_channel)))
406
            basic.append(RadioSetting("squelch_level", "Squelch level",
407
                         RadioSettingValueList(SQUELCH_LEVEL,
408
                         SQUELCH_LEVEL[self.memobj.squelch_level])))
409
            basic.append(RadioSetting("scan_resume", "Scan resume",
410
                         RadioSettingValueList(SCAN_RESUME,
411
                         SCAN_RESUME[self.memobj.scan_resume])))
412
            basic.append(RadioSetting("scan_pause", "Scan pause",
413
                         RadioSettingValueList(SCAN_PAUSE,
414
                         SCAN_PAUSE[self.memobj.scan_pause])))
415
            basic.append(RadioSetting("beep_volume", "Beep audio",
416
                         RadioSettingValueList(BEEP_VOLUME,
417
                         BEEP_VOLUME[self.memobj.beep_volume])))
418
            basic.append(RadioSetting("beep", "Operation beep",
419
                         RadioSettingValueBoolean(self.memobj.beep)))
420
            basic.append(RadioSetting("backlight", "LCD backlight",
421
                         RadioSettingValueList(BACKLIGHT,
422
                         BACKLIGHT[self.memobj.backlight])))
423
            basic.append(RadioSetting("busy_led", "Busy LED",
424
                         RadioSettingValueBoolean(self.memobj.busy_led)))
425
            basic.append(RadioSetting("auto_power_off", "Auto power off",
426
                         RadioSettingValueList(AUTO_POWER_OFF,
427
                         AUTO_POWER_OFF[self.memobj.auto_power_off])))
428
            basic.append(RadioSetting("power_save", "Power save",
429
                         RadioSettingValueList(POWER_SAVE,
430
                         POWER_SAVE[self.memobj.power_save])))
431
            basic.append(RadioSetting("monitor", "Monitor",
432
                         RadioSettingValueList(MONITOR,
433
                         MONITOR[self.memobj.monitor])))
434
            basic.append(RadioSetting("dial_speedup", "Dial speedup",
435
                         RadioSettingValueBoolean(self.memobj.dial_speedup)))
436
            basic.append(RadioSetting("auto_repeater", "Auto repeater",
437
                         RadioSettingValueList(AUTO_REPEATER,
438
                         AUTO_REPEATER[self.memobj.auto_repeater])))
439
            basic.append(RadioSetting("hm_75a_function", "HM-75A function",
440
                         RadioSettingValueList(HM_75A_FUNCTION,
441
                         HM_75A_FUNCTION[self.memobj.hm_75a_function])))
442
            basic.append(RadioSetting("wx_alert", "WX alert",
443
                         RadioSettingValueBoolean(self.memobj.wx_alert)))
444
            basic.append(RadioSetting("wx_channel", "Current WX channel",
445
                         RadioSettingValueList(WX_CHANNEL,
446
                         WX_CHANNEL[self.memobj.wx_channel])))
447
            basic.append(RadioSetting("comment", "Comment",
448
                         RadioSettingValueString(0, COMMENT_LEN,
449
                         str(self.memobj.comment),
450
                         autopad = True)))
451
            basic.append(RadioSetting("tune_step", "Current tune step",
452
                         RadioSettingValueList(TUNE_STEP_STR,
453
                         TUNE_STEP_STR[self.memobj.tune_step])))
454
            basic.append(RadioSetting("band_selected", "Selected band",
455
                         RadioSettingValueInteger(0, BANDS - 1, self.memobj.band_selected)))
456
            basic.append(RadioSetting("memory_display", "Memory display",
457
                         RadioSettingValueList(MEMORY_DISPLAY,
458
                         MEMORY_DISPLAY[self.memobj.memory_display])))
459
            basic.append(RadioSetting("memory_name", "Memory name",
460
                         RadioSettingValueBoolean(self.memobj.memory_name)))
461
            basic.append(RadioSetting("dial_select", "Dial select",
462
                         RadioSettingValueList(DIAL_SELECT,
463
                         DIAL_SELECT[self.memobj.dial_select])))
464
            basic.append(RadioSetting("power", "RF power",
465
                         RadioSettingValueList(POWER,
466
                         POWER[self.memobj.power])))
467
            basic.append(RadioSetting("vfo", "Current VFO",
468
                         RadioSettingValueList(VFO,
469
                         VFO[self.memobj.vfo])))
470
            basic.append(RadioSetting("attenuator", "RF attenuator",
471
                         RadioSettingValueBoolean(self.memobj.attenuator)))
472
            basic.append(RadioSetting("skip_scan", "Skip scan",
473
                         RadioSettingValueBoolean(self.memobj.skip_scan)))
474
# TODO: this needs to be reverse engineered, because the following commented
475
# code does not seem correct
476
#            basic.append(RadioSetting("mode", "Current mode",
477
#                         RadioSettingValueList(OPERATION_MODE,
478
#                         OPERATION_MODE[self.memobj.mode])))
479
            basic.append(RadioSetting("vfo_scan", "VFO scan",
480
                         RadioSettingValueList(VFO_SCAN,
481
                         VFO_SCAN[self.memobj.vfo_scan])))
482
            basic.append(RadioSetting("memory_scan", "Memory scan",
483
                         RadioSettingValueList(MEMORY_SCAN,
484
                         MEMORY_SCAN[self.memobj.memory_scan])))
485
            basic.append(RadioSetting("tv_channel", "Current TV channel",
486
                         RadioSettingValueInteger(0, TV_CHANNELS - 1, self.memobj.tv_channel)))
487

    
488
            # DTMF auto dial
489
            dtmf_autodial.append(RadioSetting("autodial", "Autodial",
490
                                 RadioSettingValueList(AUTODIAL,
491
                                 AUTODIAL[self.memobj.autodial])))
492
            dtmf_autodial.append(RadioSetting("dtmf_speed", "Speed",
493
                                 RadioSettingValueList(DTMF_SPEED,
494
                                 DTMF_SPEED[self.memobj.dtmf_speed])))
495
            for x in range(DTMF_AUTODIAL_NUM):
496
                rs = RadioSetting("dtmf_codes[%d].dtmf_digits" % x, "DTMF autodial: %d" % x,
497
                                  RadioSettingValueString(0, DTMF_DIGITS_NUM,
498
                                  self.dtmf_icom2chirp(self.memobj.dtmf_codes[x].dtmf_digits),
499
                                  autopad = True, charset = "0123456789ABCD*#abcd "))
500
                rs.set_apply_callback(self.apply_dtmf_autodial, self.memobj.dtmf_codes[x].dtmf_digits)
501
                dtmf_autodial.append(rs)
502

    
503
            # expand 1
504
            expand_1.append(RadioSetting("expand_1", "Expand 1",
505
                            RadioSettingValueBoolean(self.memobj.expand_1)))
506
            expand_1.append(RadioSetting("scan_stop_beep", "Scan stop beep",
507
                            RadioSettingValueBoolean(self.memobj.scan_stop_beep)))
508
            expand_1.append(RadioSetting("scan_stop_light", "Scan stop light",
509
                            RadioSettingValueBoolean(self.memobj.scan_stop_light)))
510
            expand_1.append(RadioSetting("light_postion", "Light position",
511
                            RadioSettingValueList(LIGHT_POSITION,
512
                            LIGHT_POSITION[self.memobj.light_position])))
513
            expand_1.append(RadioSetting("light_color", "Light color",
514
                            RadioSettingValueList(LIGHT_COLOR,
515
                            LIGHT_COLOR[self.memobj.light_color])))
516
            expand_1.append(RadioSetting("band_edge_beep", "Band edge beep",
517
                            RadioSettingValueBoolean(self.memobj.band_edge_beep)))
518
            expand_1.append(RadioSetting("auto_power_on", "Auto power on",
519
                            RadioSettingValueList(AUTO_POWER_ON,
520
                            AUTO_POWER_ON[self.memobj.auto_power_on])))
521
            expand_1.append(RadioSetting("key_lock", "Key lock",
522
                            RadioSettingValueList(KEY_LOCK,
523
                            KEY_LOCK[self.memobj.key_lock])))
524
            expand_1.append(RadioSetting("ptt_lock", "PTT lock",
525
                            RadioSettingValueBoolean(self.memobj.ptt_lock)))
526
            expand_1.append(RadioSetting("lcd_contrast", "LCD contrast",
527
                            RadioSettingValueList(LCD_CONTRAST,
528
                            LCD_CONTRAST[self.memobj.lcd_contrast])))
529
            expand_1.append(RadioSetting("opening_message", "Opening message",
530
                            RadioSettingValueBoolean(self.memobj.opening_message)))
531
            expand_1.append(RadioSetting("opening_message_text", "Opening message",
532
                            RadioSettingValueString(0, OPENING_MESSAGE_LEN,
533
                            str(self.memobj.opening_message_text),
534
                            autopad = True, charset = CHARSET)))
535

    
536
            # expand 2
537
            expand_2.append(RadioSetting("expand_2", "Expand 2",
538
                            RadioSettingValueBoolean(self.memobj.expand_2)))
539
            expand_2.append(RadioSetting("busy_lockout", "Busy lock out",
540
                            RadioSettingValueBoolean(self.memobj.busy_lockout)))
541
            expand_2.append(RadioSetting("timeout_timer", "Timeout timer",
542
                            RadioSettingValueList(TIMEOUT_TIMER,
543
                            TIMEOUT_TIMER[self.memobj.timeout_timer])))
544
            expand_2.append(RadioSetting("active_band", "Active band",
545
                            RadioSettingValueList(ACTIVE_BAND,
546
                            ACTIVE_BAND[self.memobj.active_band])))
547
            expand_2.append(RadioSetting("fm_narrow", "FM narrow",
548
                            RadioSettingValueBoolean(self.memobj.fm_narrow)))
549
            expand_2.append(RadioSetting("split", "Split",
550
                            RadioSettingValueBoolean(self.memobj.split)))
551
            expand_2.append(RadioSetting("morse_code_enable", "Morse code synthesizer",
552
                            RadioSettingValueBoolean(self.memobj.morse_code_enable)))
553
            expand_2.append(RadioSetting("morse_code_speed", "Morse code speed",
554
                            RadioSettingValueList(MORSE_CODE_SPEED,
555
                            MORSE_CODE_SPEED[self.memobj.morse_code_speed])))
556

    
557
            return group
558
        except:
559
            import traceback
560
            LOG.error("Failed to parse settings: %s", traceback.format_exc())
561
            return None
562

    
563
    def set_settings(self, settings):
564
        for element in settings:
565
            if not isinstance(element, RadioSetting):
566
                self.set_settings(element)
567
                continue
568
            if not element.changed():
569
                continue
570
            try:
571
                if element.has_apply_callback():
572
                    LOG.debug("Using apply callback")
573
                    try:
574
                        element.run_apply_callback()
575
                    except NotImplementedError as e:
576
                        LOG.error("icx90: %s", e)
577
                    continue
578

    
579
                # Find the object containing setting.
580
                obj = self.memobj
581
                bits = element.get_name().split(".")
582
                setting = bits[-1]
583
                for name in bits[:-1]:
584
                    if name.endswith("]"):
585
                        name, index = name.split("[")
586
                        index = int(index[:-1])
587
                        obj = getattr(obj, name)[index]
588
                    else:
589
                        obj = getattr(obj, name)
590

    
591
                try:
592
                    old_val = getattr(obj, setting)
593
                    LOG.debug("Setting %s(%r) <= %s" % (
594
                        element.get_name(), old_val, element.value))
595
                    setattr(obj, setting, element.value)
596
                except AttributeError as e:
597
                    LOG.error("Setting %s is not in the memory map: %s" %
598
                              (element.get_name(), e))
599
            except Exception as e:
600
                LOG.debug(element.get_name())
601
                raise
602

    
603
    def process_mmap(self):
604
        self.memobj = bitwise.parse(ICX90_MEM_FORMAT, self._mmap)
605

    
606
    def get_raw_memory(self, number):
607
        (mem_item, special, unique_idx) = self.get_mem_item(number)
608
        return repr(mem_item)
609

    
610
    def sync_in(self):
611
        icf.IcomCloneModeRadio.sync_in(self)
612
        self.process_mmap()
613

    
614
    def sync_out(self):
615
        icf.IcomCloneModeRadio.sync_out(self)
616

    
617
    def freq_chirp2icom(self, freq):
618
        if chirp_common.is_fractional_step(freq):
619
            mult = 6250
620
            multr = 1
621
        else:
622
            mult = 5000
623
            multr = 0
624

    
625
        return (freq / mult, multr)
626

    
627
    def freq_icom2chirp(self, freq, mult):
628
        return freq * (6250 if mult else 5000)
629

    
630
    def get_skip(self, number):
631
        bank_item = self.memobj.banks[number]
632
        if bank_item.prog_skip:
633
            return "P"
634
        elif bank_item.mem_skip:
635
            return "S"
636
        return ""
637

    
638
    def set_skip(self, number, skip):
639
        bank_item = self.memobj.banks[number]
640
        if skip == "P":
641
            bank_item.prog_skip = 1
642
            bank_item.mem_skip = 1
643
        elif skip == "S":
644
            bank_item.prog_skip = 0
645
            bank_item.mem_skip = 1
646
        elif skip == "":
647
            bank_item.prog_skip = 0
648
            bank_item.mem_skip = 0
649
        else:
650
            raise errors.InvalidDataError("skip '%s' not supported" % skip)
651

    
652
    # returns (memobj.mem_item, is_special_channel, unique_idx)
653
    def get_mem_item(self, number):
654
        try:
655
            item_type = self.special[number]["item_type"]
656
            num = self.special[number]["num"]
657
            unique_idx = self.special[number]["uidx"]
658
            if item_type == "scan_edge":
659
                return (self.memobj.scan_edges[num], True, unique_idx)
660
            elif item_type == "call_chan":
661
                return (self.memobj.call_channels[num], True, unique_idx)
662
            elif item_type == "vfo_a":
663
                return (self.memobj.vfo_a_band[num], True, unique_idx)
664
            elif item_type == "vfo_b":
665
                return (self.memobj.vfo_b_band[num], True, unique_idx)
666
            else:
667
                raise errors.InvalidDataError("unknown special channel type '%s'" % item_type)
668
        except KeyError:
669
            return (self.memobj.memory[number], False, number)
670

    
671
    def get_raw_memory(self, number):
672
        (mem_item, special, unique_idx) = self.get_mem_item(number)
673
        return repr(mem_item)
674

    
675
    def get_memory(self, number):
676
        mem = chirp_common.Memory()
677

    
678
        (mem_item, special, unique_idx) = self.get_mem_item(number)
679

    
680
        freq = self.freq_icom2chirp(mem_item.freq, mem_item.freq_mult)
681
        if freq == 0:
682
            mem.empty = True
683
        else:
684
            mem.empty = False
685
            mem.freq = freq
686
            if special:
687
                mem.name = " " * NAME_LENGTH
688
            else:
689
                mem.name = str(mem_item.name).rstrip("\x00 ")
690
            mem.rtone = chirp_common.TONES[(mem_item.tx_tone_hi << 4) + mem_item.tx_tone_lo]
691
            mem.ctone = chirp_common.TONES[mem_item.rx_tone]
692
            mem.dtcs = chirp_common.DTCS_CODES[mem_item.dtcs]
693
            mem.dtcs_polarity = DTCS_POLARITY[mem_item.dtcs_polarity]
694
            mem.offset = self.freq_icom2chirp(mem_item.offset_freq, mem_item.offset_freq_mult)
695
            mem.duplex = DUPLEX[mem_item.duplex]
696
            mem.tmode = TONE_MODE[mem_item.tone_mode]
697
            mem.tuning_step = TUNE_STEP[mem_item.tune_step]
698
            mem.mode = MODE[mem_item.mode]
699
            if not special:
700
                mem.skip = self.get_skip(number)
701
        if special:
702
           mem.extd_number = number
703
           mem.number = -len(self.special) + unique_idx
704
        else:
705
           mem.number = number
706

    
707
        return mem
708

    
709
    def set_memory(self, memory):
710
        (mem_item, special, unique_idx) = self.get_mem_item(memory.number)
711
        if memory.empty:
712
            mem_item.set_raw("\x00" * MEM_ITEM_SIZE)
713
            self.clear_bank(memory.number)
714
            self.memobj.banks[memory.number].invisible_channel = 1
715
        else:
716
            (mem_item.freq, mem_item.freq_mult) = self.freq_chirp2icom(memory.freq)
717
            if special:
718
                mem_item.name = " " * NAME_LENGTH
719
            else:
720
                self.memobj.banks[memory.number].invisible_channel = 0
721

    
722
                for x in range(NAME_LENGTH):
723
                    try:
724
                        mem_item.name[x] = str(memory.name[x])
725
                    except IndexError:
726
                        mem_item.name[x] = " "
727
            mem_item.tx_tone_hi = chirp_common.TONES.index(memory.rtone) >> 4
728
            mem_item.tx_tone_lo = chirp_common.TONES.index(memory.rtone) & 0x0f
729
            mem_item.rx_tone = chirp_common.TONES.index(memory.ctone)
730
            mem_item.dtcs = chirp_common.DTCS_CODES.index(memory.dtcs)
731
            mem_item.dtcs_polarity = DTCS_POLARITY.index(memory.dtcs_polarity)
732
            (mem_item.offset_freq, mem_item.offset_freq_mult) = self.freq_chirp2icom(memory.offset)
733
            mem_item.duplex = DUPLEX.index(memory.duplex)
734
            mem_item.tone_mode = TONE_MODE.index(memory.tmode)
735
            mem_item.tune_step = TUNE_STEP.index(memory.tuning_step)
736
            mem_item.mode = MODE.index(memory.mode)
737
            if not special:
738
                self.set_skip(memory.number, memory.skip)
739

    
740
    def get_bank_model(self):
741
        return ICx90BankModel(self)
742

    
743
class ICx90Radio_ham(ICx90Radio):
744

    
745
    def get_features(self):
746
        rf = ICx90Radio.get_features(self)
747
        rf.has_sub_devices = False
748

    
749
        return rf
750

    
751
class ICx90Radio_tv(ICx90Radio):
752
    VARIANT = "TV"
753

    
754
    def get_features(self):
755
        rf = chirp_common.RadioFeatures()
756
        rf.has_settings = True
757
        rf.has_name = True
758
        rf.has_bank = False
759
        rf.has_bank_index = False
760
        rf.has_bank_names = False
761
        rf.can_delete = True
762
        rf.has_ctone = False
763
        rf.has_dtcs = False
764
        rf.has_dtcs_polarity = False
765
        rf.has_tuning_step = False
766
        rf.has_comment = False
767
        rf.has_sub_devices = False
768
        rf.memory_bounds = (0, TV_CHANNELS - 1)
769
        rf.valid_characters = CHARSET
770
        rf.valid_modes = list(TV_MODE)
771
        rf.valid_tmodes = []
772
        rf.valid_duplexes = [""]
773
        rf.valid_tuning_steps = []
774
        rf.valid_bands = [(46750000, 957750000)]
775
        rf.valid_skips = ["", "S"]
776
        rf.valid_name_length = TV_NAME_LENGTH
777
        rf.valid_special_chans = []
778

    
779
        return rf
780

    
781
    def get_bank_model(self):
782
        return None
783

    
784
    def freq_chirp2icom(self, freq):
785
        return freq / 5000
786

    
787
    def freq_icom2chirp(self, freq):
788
        return freq * 5000
789

    
790
    def get_skip(self, number):
791
        if self.memobj.tv_channel_skip[number] == 2:
792
            return "S"
793
        return ""
794

    
795
    def set_skip(self, number, skip):
796
        if skip == "S":
797
            self.memobj.tv_channel_skip[number] = 2
798
        elif skip == "":
799
            self.memobj.tv_channel_skip[number] = 0
800
        else:
801
            raise errors.InvalidDataError("skip '%s' not supported" % skip)
802

    
803
    def get_raw_memory(self, number):
804
        return repr(self.memobj.tv_memory[number])
805

    
806
    def get_memory(self, number):
807
        mem = chirp_common.Memory()
808

    
809
        mem_item = self.memobj.tv_memory[number]
810

    
811
        mem.freq = self.freq_icom2chirp(mem_item.freq)
812
        if self.memobj.tv_channel_skip[number] == 1:
813
            mem.empty = True
814
            mem.mode = TV_MODE[0]
815
        else:
816
            mem.empty = False
817
            mem.name = str(mem_item.name).rstrip("\x00 ")
818
            mem.mode = TV_MODE[mem_item.mode]
819
            mem.skip = self.get_skip(number)
820
        mem.number = number
821

    
822
        return mem
823

    
824
    def set_memory(self, memory):
825
        mem_item = self.memobj.tv_memory[memory.number]
826
        if memory.empty:
827
            self.memobj.tv_channel_skip[memory.number] = 1
828
            mem_item.set_raw("\x00" * TV_MEM_ITEM_SIZE)
829
        else:
830
            mem_item.freq = self.freq_chirp2icom(memory.freq)
831
            for x in range(TV_NAME_LENGTH):
832
                try:
833
                    mem_item.name[x] = str(memory.name[x])
834
                except IndexError:
835
                    mem_item.name[x] = " "
836

    
837
            mem_item.mode = TV_MODE.index(memory.mode)
838
            self.set_skip(memory.number, memory.skip)
839

    
840
def dump_banks(icx90, template_file):
841
    mb = icx90.get_features().memory_bounds
842
    with open(template_file, "w") as f:
843
        for mi in range(mb[0], mb[1] + 1):
844
            mem = icx90.get_memory(mi)
845
            bank = icx90._get_bank(mi)
846
            if bank is not None:
847
                bank = BANK_INDEX[bank]
848
            bank_pos = icx90._get_bank_index(mi)
849
            if not mem.empty and bank is not None and bank_pos is not None:
850
                f.write("%s;%s;%d\n" % (mem.name, bank, bank_pos))
851

    
852
def read_template_file(template_file):
853
    banks_templ = {}
854
    with open(template_file, "r") as f:
855
        for line in f:
856
            l = line.split(";")
857
            l[1] = BANK_INDEX.index(l[1])
858
            banks_templ[l[0]] = l[1:]
859
    return banks_templ
860

    
861
def reorder_banks(icx90, preserve_position, preserve_unknown, banks_templ):
862
    banks_cnt = []
863
    mb = icx90.get_features().memory_bounds
864
    for i in range(0, BANKS):
865
        banks_cnt.append(0)
866
    for mi in range(mb[0], mb[1] + 1):
867
        mem = icx90.get_memory(mi)
868
        if preserve_unknown:
869
            bank = icx90._get_bank(mi)
870
            bank_pos = icx90._get_bank_index(mi)
871
        else:
872
            bank = None
873
            bank_pos = 0
874
        if not mem.empty:
875
            if mem.name in banks_templ:
876
                bank = int(banks_templ[mem.name][0])
877
                if preserve_position:
878
                    bank_pos = int(banks_templ[mem.name][1])
879
                else:
880
                    bank_pos = banks_cnt[bank]
881
                    banks_cnt[bank] += 1
882
                print("%s\t-> %s, %02d" % (mem.name, BANK_INDEX[bank], bank_pos))
883
            # explicitly set non empty channel as visible
884
            icx90.memobj.banks[mi].invisible_channel = 0
885
        if bank >= BANKS or bank_pos >= BANK_NUM:
886
            bank = None
887
            bank_pos = 0
888
        icx90._set_bank(mi, bank)
889
        icx90._set_bank_index(mi, bank_pos)
890

    
891
if __name__ == "__main__":
892
    parser = argparse.ArgumentParser(description="Icom IC-E90 banks handling helper.")
893
    parser.add_argument("icx90_img_file", help="IC-X90 IMG file.")
894
    parser.add_argument("template_file", help="Banks template file.")
895
    parser.add_argument("-r", "--read-banks", action="store_true",
896
                        help="Read banks content and store it to template file.")
897
    parser.add_argument("-f", "--fix-banks", action="store_true",
898
                        help="Fix banks content, reorder channels in banks according to the provided template file and write it to IMG file.")
899
    parser.add_argument("-p", "--preserve-position", action="store_true",
900
                        help="Preserve bank position as in the template file if possible, otherwise put channels to banks according their position in the memory.")
901
    parser.add_argument("-u", "--preserve-unknown", action="store_true",
902
                        help="Preserve channels in banks if they aren't in the template file and don't conflicts with the template file, otherwise remove them from the banks.")
903
    parser.add_argument("-b", "--backup_img", action="store_true",
904
                        help="Backup IMG file before changing it.")
905

    
906
    args = vars(parser.parse_args())
907

    
908
    options_ok = True
909
    try:
910
        icx90_img_file = str(args.pop("icx90_img_file"))
911
        template_file = str(args.pop("template_file"))
912
    except KeyError:
913
        options_ok = False
914

    
915
    if options_ok and (args["read_banks"] or args["fix_banks"]):
916
        icx90 = ICx90Radio(icx90_img_file)
917
        if args["read_banks"]:
918
            dump_banks(icx90, template_file)
919
        elif args["fix_banks"]:
920
            banks_templ = read_template_file(template_file)
921
            if args["backup_img"]:
922
                icx90.save_mmap(icx90_img_file + ".bak")
923
            reorder_banks(icx90, args["preserve_position"], args["preserve_unknown"], banks_templ)
924
            icx90.save_mmap(icx90_img_file)
925
    else:
926
        parser.print_help()
(3-3/7)