-
Notifications
You must be signed in to change notification settings - Fork 6
/
DM1702_contact.py
434 lines (398 loc) · 15.5 KB
/
DM1702_contact.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
# -*- coding: utf-8 -*-
from __future__ import print_function
from struct import *
from array import array
import sys
from DM1702_data_maps import *
callTypes = {
'private' : 0x3,
'group' : 0x4,
'all' : 0x5
}
MDCallNames = {
0x3 : 'Private Call',
0x4 : 'Group Call',
0x5 : 'All Call'
}
callSorting = {
'callSign' : 'S',
'id' : 'I',
'name' : 'N'
}
specialPrivate = {
9990
}
contactFormats = {
'CPS' : {
'info' : 'MD1702 internal XLS format for copy & paste',
'fields': ['No.', 'Call Alias' , 'Call Type', 'Call ID'],
'quotechar' : None,
'delimiter': ',' ,
'seek' : None,
'fixed' : {},
'number': 'No.',
'callSign' : 'Call Alias',
'callTypes' : {'Private Call' : 3, 'Group Call' : 4, 'All Call': 5},
'callType': 'Call Type',
'id' : 'Call ID',
'name': None,
'country' : None
},
'dmrid' : {
'info' : 'https://ham-digital.org/user-by-call.php',
'fields': ['num', 'dmrid', 'callsign', 'name', 'country', 'ctry', 'dev_id'],
'quotechar' : None,
'delimiter': ';' ,
'seek' : None,
'fixed' : {},
'number': 'num',
'callSign' : 'callsign',
'callTypes': None,
'callType': None,
'id' : 'dmrid',
'name': 'name',
'country' : 'ctry'
},
'bmgroup' : {
'info' : 'BrandMeister Talkgroups CSV export from https://brandmeister.network/?page=talkgroups',
'fields': ['Country','Talkgroup','Name',''],
'quotechar' : '"',
'delimiter': ',' ,
'seek' : None,
'fixed' : {},
'number': None,
'callSign' : 'Name',
'callTypes': None,
'callType': 4,
'id' : 'Talkgroup',
'name': None,
'country' : None
},
'bmuser' : {
'info' : 'BrandMeister User CSV export from https://brandmeister.network/?page=contactsexport',
'fields': ['ID','Call','Name','Last TX', 'TX Count'],
'quotechar' : '"',
'delimiter': ',' ,
'seek' : None,
'fixed' : {},
'number': None,
'callSign' : 'Call',
'callTypes': None,
'callType': 3,
'id' : 'ID',
'name': 'Name',
'country' : None
},
'RT3S' : {
'info' : 'Downloads at https://www.ailunce.com/ResourceCenter',
'fields': ['Radio ID', 'CallSign', 'Name', 'NickName', 'City', 'State', 'Country'],
'quotechar' : None,
'delimiter': ',' ,
'seek' : 3,
'fixed' : {},
'number': None,
'callSign' : 'CallSign',
'callTypes': None,
'callType': None,
'id' : 'Radio ID',
'name': 'Name',
'country' : 'Country'
},
'MD380CPS' : {
'info' : 'MD380 CPS format',
'fields': ['Contact Name', 'Call Type', 'Call ID', 'Call Receive Tone'],
'quotechar' : None,
'delimiter': ',' ,
'seek' : None,
'fixed' : {'Call Receive Tone' : 1 },
'number': None,
'callSign' : 'Contact Name',
'callTypes' : {'2' : 3, '1' : 4, '3': 5},
'callType': 'Call Type',
'id' : 'Call ID',
'name': None,
'country' : None
},
}
class DM1702_contact(object):
sort_by = callSorting['callSign']
csv_idx = 0
contact_len = 0x18
def __init__(self, cid, call, name=None, country=None, ctype = None):
self.call=call
self.name=name
self.cid=int(cid)
self.country=country
if isinstance(ctype, int):
self.type = ctype
elif ctype in callTypes:
self.type= callTypes[ctype]
else:
# Try heuristics to determine type
if self.cid == 16777215:
self.type = callTypes['all']
elif (self.cid > 5000 or self.cid < 4000) and self.cid < 1000000 \
and (self.cid not in specialPrivate):
self.type = callTypes['group']
else:
self.type = callTypes['private']
@staticmethod
def set_sort(what=callSorting['callSign']):
DM1702_contact.sort_by = what.upper()
# @staticmethod
# def csv_hdr():
# csv_idx = 0
# return "Radio ID,CallSign,Name,NickName,City,State,Country"
#
# @staticmethod
# def csv_dmrid_hdr():
# csv_idx = 0
# return "num;dmrid;callsign;name;country;ctry;dev_id"
#
# @staticmethod
# def cps_csv_hdr():
# csv_idx = 0
# return "No.,Call Alias,Call Type,Call ID"
#
@staticmethod
def from_MD_record(data):
call, tcid = unpack('<2x16sxLx', data)
call = call.decode(errors="ignore").split('\x00')[0]
cid = tcid & 0xffffff
ctype = (tcid >> 24) & 0xf
#print(call, cid, ctype)
return DM1702_contact(cid, call, ctype = ctype)
# This will be probably slow :-(
def cmp(self, other):
if DM1702_contact.sort_by == 'N' :
s1 = self.name
s2 = other.name
elif DM1702_contact.sort_by == 'I' :
s1 = self.cid
s2 = other.cid
else:
s1 = "%s%i" % (self.country, self.cid)
s2 = "%s%i" % (other.country, other.cid)
return -1 if s1 < s2 else (1 if s1 > s2 else 0)
def __str__(self):
return self.call
def __float__(self):
return self.cid + (0.0 if self.type == 3 else 0.1)
def __int__(self):
return self.cid
def __lt__(self, other):
return self.cmp(other) < 0
# def __gt__(self, other):
# return self.cmp(other) > 0
#
def __eq__(self, other):
if isinstance(other, str):
s1 = str(self)
elif isinstance(other, int):
s1 = int(self)
elif isinstance(other, float):
s1 = float(self)
else:
return self.cid == other.cid and self.call == other.call and self.type == other.type
return s1 == other
def to_MD_record(self):
return pack('<2s16scLc', b'\xff\xff', str(self.call[:16]) if b"" == "" else bytes(self.call[:16],"utf-8"), b'\xff', (self.type << 24) | self.cid, b'\xff')
#return pack('<2x16sxLx', str(self.call[:16]) if b"" == "" else bytes(self.call[:16],"utf-8"), (self.type << 24) | self.cid)
def to_cps_csv(self):
DM1702_contact.csv_idx += 1
return ("%i,%s,%s,%i" % (self.csv_idx, self.call, MDCallNames[self.type], self.cid))
def __repr__(self):
return repr({ 'id' : self.cid, 'call' : self.call, 'type' : self.type })
class DM1702_contacts(object):
max_internal_contacts = 800
def __init__(self, contact_data=None, contact_map=None):
self.clist = []
self.index = 0
self.str_map = {}
self.int_map = {}
self.float_map = {}
if contact_data is not None and contact_map is not None:
self.import_CP(contact_data, contact_map)
def append(self, contact):
idx = len(self.clist)
if float(contact) in self.float_map: #Duplicate contact DMR ID not allowed
return
elif str(contact) in self.str_map:
if self.clist[self.str_map[str(contact)]] == contact:
return #Duplicate contact entry not allowed
elif float(contact) not in self.float_map:
#Duplicate call with different ID - allowed with different label
i = 1
call = contact.call[:13]
while True:
call2 = "%s-%i" % (call, i)
i += 1
if call2 not in self.str_map:
contact.call = call2
break
if self.clist[self.str_map[str(contact)]] == contact:
return #If already inserted, skip it
self.clist.append(contact)
self.str_map[str(contact)] = self.int_map[int(contact)] = self.float_map[float(contact)] = idx
def sort(self, by=None):
self.str_map = {}
self.int_map = {}
self.float_map = {}
if by is not None: DM1702_contact.set_sort(by)
self.clist.sort()
for idx in range(0,len(self.clist)) :
ct = self.clist[idx]
self.str_map[str(ct)] = self.int_map[int(ct)] = self.float_map[float(ct)] = idx
def get_index(self, what):
if isinstance(what, str) and what in self.str_map:
return self.str_map[what]
elif isinstance(what, int) and what in self.int_map:
return self.int_map[what]
elif isinstance(what, float) and what in self.float_map:
return self.float_map[what]
elif isinstance(what, DM1702_contact) and float(what) in self.float_map:
return self.float_map[float(what)]
else:
return None
def __getitem__(self, what):
idx = self.get_index(what)
return None if idx is None else self.clist[idx]
def __len__(self):
return len(self.clist)
def import_CP(self, contact_data, contact_map):
cnt, gr_calls, all_call_ind = unpack("<HHB11x", bytes(bytearray(contact_map[0:0x10])))
bmap=DM1702_util.get_data_bitmap(contact_map[0x10:0x74])
indices1 = unpack("<800H", bytes(bytearray(contact_map[0x100:0x740])))
indices1 = [ (x & 0xfff) for x in indices1 if x != 0xF000]
i = c = 0
#print("Count: %i, group: %i, All: %i, Alloc: %i, Ind: %i" % (cnt, gr_calls, all_call_ind, bmap.count(True), len(indices1)))
##Previous version of code checking indices instead of bitmap
#for ent in range(0, cnt):
# if (ent+1) in indices1:
# cont = DM1702_contact.from_MD_record(bytes(\
# bytearray(contact_data[i:i+DM1702_contact.contact_len])))
# self.append(cont)
# c += 1
# i += DM1702_contact.contact_len
for ent in range(0, len(bmap)):
if bmap[ent]:
cont = DM1702_contact.from_MD_record(bytes(\
bytearray(contact_data[i:i+DM1702_contact.contact_len])))
self.append(cont)
i += DM1702_contact.contact_len
def export_CP(self):
contact_data = []
cnt = len(self)
if cnt > self.max_internal_contacts:
cnt = self.max_internal_contacts
gr_calls = all_call_ind = 0
for c in self.clist:
if c.type == callTypes['group']:
gr_calls += 1
elif c.type == callTypes['all']:
all_call_ind = 1
contact_map = pack("<HHB11s", cnt, gr_calls, all_call_ind, b'\xff' * 11)
contact_map += b'\x00' * int(cnt / 8)
contact_map += [b'\xff',b'\xfe',b'\xfc',b'\xf8',b'\xf0',b'\xe0',b'\xc0',b'\x80',b'\x00'][cnt % 8]
contact_map = DM1702_util.pad_data(contact_map, 0x76)
contact_map += b'\x00\x00\xff\xff\xff\xff\xfe' + (b'\xff' * (0x100-0x7d))
skipped = skipped2 = 0
#Add Alphabetic indices
for sid in sorted(self.str_map):
if self.str_map[sid] < self.max_internal_contacts:
ctact = self.clist[self.str_map[sid]]
item = (self.str_map[sid]+1) | (ctact.type << 12)
contact_map += bytes(bytearray([item & 0xff, item >> 8]))
else:
skipped += 1
contact_map += b'\x00\xf0' * int((0x740 - len(contact_map))/2)
#Add Numeric indices
for sid in sorted(self.float_map):
if self.float_map[sid] < self.max_internal_contacts:
ctact = self.clist[self.float_map[sid]]
item = (self.float_map[sid]+1) | (ctact.type << 12)
contact_map += bytes(bytearray([item & 0xff, item >> 8]))
else:
skipped2 += 1
assert skipped == skipped2
contact_map += b'\x00\xf0' * int((0xd80 - len(contact_map))/2)
contact_map = [x for x in contact_map]
contact_data = []
for c in self.clist:
contact_data += c.to_MD_record()
return contact_map, contact_data, skipped
def load(self, infile, ftype="auto"):
import csv
with open(infile, 'r') as f:
if ftype is "auto":
l=f.readline()
sep = ';' if ';' in l else (',' if ',' in l else '@')
f.seek(0)
for fmt in contactFormats:
if contactFormats[fmt]['callSign'] in l and \
contactFormats[fmt]['id'] in l and \
contactFormats[fmt]['delimiter'] == sep:
sys.stderr.write("Contact format %s detected\n" % fmt)
ftype = fmt
if contactFormats[fmt]['seek'] is not None and l.index(contactFormats[fmt]['fields'][0]) != 0:
f.seek(contactFormats[fmt]['seek'])
break
if ftype is "auto":
raise Exception('Input contact file format not recognized')
cf = contactFormats[fmt]
csv_reader = csv.DictReader(f, delimiter=sep)
for row in csv_reader:
#print(row)
cs=row[cf['callSign']]
cid=row[cf['id']]
calltype = name = country = None
if cf['callType'] is not None:
if cf['callType'] in row:
calltype=row[cf['callType']]
elif isinstance(cf['callType'], int):
calltype = cf['callType']
if calltype == '':
calltype = None
if isinstance(cf['callTypes'], dict) and calltype in cf['callTypes']:
calltype = cf['callTypes'][calltype]
if cf['name'] is not None and cf['name'] in row and row[cf['name']] != '':
name = row[cf['name']]
if cf['country'] is not None and cf['country'] in row and row[cf['country']] != '':
country = row[cf['country']]
self.append(DM1702_contact(cid, cs, name, country, calltype))
def save(self, outfile, ftype):
import csv
if ftype.lower() == 'list':
sys.stderr.write('Supported output formats (%i)' % len(contactFormats))
for cf in contactFormats:
sys.stderr.write('\n%10s: %s' % (cf, contactFormats[cf]['info']))
sys.stderr.write('\n')
return
elif ftype not in contactFormats:
raise Exception('Output contact file format not recognized')
cf = contactFormats[ftype]
ct = None
if isinstance(cf['callTypes'], dict):
ct = {}
for (k,v) in cf['callTypes'].items(): ct[v] = k
with open(outfile, 'w') as f:
if cf['quotechar'] is None:
writer = csv.DictWriter(f, fieldnames=cf['fields'], delimiter=cf['delimiter'])
else:
writer = csv.DictWriter(f, fieldnames=cf['fields'], delimiter=cf['delimiter'], quotechar=cf['quotechar'])
writer.writeheader()
i = 1
for item in self.clist:
row = dict(cf['fixed'])
if cf['number'] is not None:
row[cf['number']] = i
i += 1
if cf['callSign'] is not None: row[cf['callSign']] = item.call
if cf['id'] is not None: row[cf['id']] = item.cid
if cf['name'] is not None: row[cf['name']] = item.name
if cf['country'] is not None: row[cf['country']] = item.country
if isinstance(cf['callType'], str) and ct is not None and item.type in ct:
row[cf['callType']] = ct[item.type]
writer.writerow(row)
def __repr__(self):
return repr(self.clist)