-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdbctool.py
More file actions
2097 lines (1931 loc) · 73.6 KB
/
dbctool.py
File metadata and controls
2097 lines (1931 loc) · 73.6 KB
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""A tool to read and manipulate dbc files.
The module has a Parser class with a metohd that parses the content of a \
dbc file held in a string and returns the content on an intermediate format \
in the form of a list of parsed dbc-sections. This intermediate format can \
be used to initialize an object of the Bus class. The objects of the Bus \
class can hold the same information as a dbc-file can, but does so in a more \
structured form. Most, but not all, dbc sections are implemented. The class \
also has a method to generate a dbc representation of the object's content.
"""
#
# Copyright 2024 Einar Halvorsen
#
# License: GPL-3.0-or-later
#
import sys
import re
import warnings
import textwrap
import pprint
def custom_formatwarning(msg, *args, **kwargs):
return str(args[0].__name__) + ": " + str(msg) + '\n'
warnings.formatwarning = custom_formatwarning
class DatabaseError(Exception):
"""Semantic errors in database.
"""
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class DatabaseWarning(Warning):
"""Warnings about inconsistencies or ambiguities and how they are resolved.
"""
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class Range():
"""A range of values from min to max.
"""
def __init__(self, l1, l2=None):
"""Initializes a Range object.
Args:
l1: Minimum value or list/tuple of min and max values.
l2: Maximum value of None if l1 is list or tuple.
"""
if l2 is None:
self.minval = l1[0]
self.maxval = l1[1]
else:
self.minval = l1
self.maxval = l2
def __str__(self):
return "Range({}, {})".format(self.minval, self.maxval)
def limits(self):
"""Returns tuple of minimum and maximum values.
"""
return (self.minval, self.maxval)
def within(self, x):
"""Returns boolean that is True iff value x is in the range.
"""
return (x >= self.minval) and (x <= self.maxval)
def __eq__(self, other):
return (other.minval == self.minval) and (other.maxval == self.maxval)
def intersection(self, other):
"""Returns intersection of range with other intersection.
"""
if self.minval > other.maxval or self.maxval < other.minval:
return None
new_max = min(self.maxval, other.maxval)
new_min = max(self.minval, other.minval)
return Range(new_min, new_max)
class Switch():
"""Class for holding mutiplexor switches.
"""
def __init__(self):
"""Initializes Switch object.
"""
self._e = []
def append(self, range, sig):
"""Append mutiplexed signal and its range of switch values.
Args:
range(Range): The range of switch values.
sig(Signal) : The signal that is multiplexed.
"""
for e in self._e:
if range == e[0] and sig == e[1]:
return
self._e.append((range, sig))
def __len__(self):
return len(self._e)
def __str__(self):
string = ""
for e in self._e:
string += str(e[0]) + " -->\n"
sigstr = str(e[1])
string += textwrap.indent(sigstr, 4*' ')
return string
def any_multiples(self):
"""Returns boolean True iff there is a signal with more than one
multiplexor range.
"""
d = {}
for _, sig in self._e:
if sig in d:
d[sig] += 1
else:
d[sig] = 1
for sig in d:
if d[sig] > 1:
return True
return False
def dbc_sg_mul_val_strs(self):
d = {}
sigs = []
for e in self._e:
sig = e[1]
signame = sig.name
r = e[0]
if signame in d:
d[signame].append(r)
else:
d[signame] = [r]
sigs.append(sig)
for signame in d:
ranges = d[signame]
rstrs = [str(r.minval) + '-' + str(r.maxval) for r in ranges]
d[signame] = ' '.join(rstrs)
return sigs, d
class Signal():
"""Class for CAN-bus signals.
"""
def __init__(self, d):
"""Initializes Signal object.
Args:
d(dict): Dictionary of parameters.
"""
self.name = d['name']
self.multiplex_value = d['multiplex_value'] # None if not multiplexed
self.is_multiplexor = d['is_multiplexor']
self.is_little_endian = d['little_endian']
self.is_signed = d['signed']
self.start_bit = d['start']
self.numbits = d['size']
self.factor = d['factor']
self.offset = d['offset']
self.range = Range(d['range']) # Range of values
self.unit = d['unit']
self.receivers = d['receivers']
self.switch = Switch()
self.comments = []
self.attributes = {}
self.value_descriptions = {}
self.value_type = None
def __str__(self):
if self.numbits == 1:
string = "{}, {} bit at bit {}".format(self.name,
self.numbits,
self.start_bit)
else:
string = "{}, {} bits starting at bit {}".format(self.name,
self.numbits,
self.start_bit)
if self.value_type == 0:
string += ', integer'
elif self.value_type == 1:
string += ', float'
elif self.value_type == 2:
string += ', double'
elif self.value_type is not None:
string += ', value type = {}'.format(self.value_type)
string += "\n"
if self.comments:
for c in self.comments:
string += c + "\n"
if self.attributes:
string += "attributes=" + str(self.attributes) + "\n"
if self.value_descriptions:
string += "value descriptions: " + str(self.value_descriptions)\
+ "\n"
if self.switch:
string += str(self.switch)
return string
def multiplexes(self, val):
"""Return boolean True if signal is a multiplexor for value.
"""
return self.is_multiplexor\
and (val >= 0) and (val < 2**self.numbits)
def dbc(self):
"""Returns dbc string of signal.
"""
string = "SG_ {} ".format(self.name)
one_more = False
if self.multiplex_value is not None:
string += "m{}".format(self.multiplex_value)
one_more = True
if self.is_multiplexor:
string += "M"
one_more = True
if one_more:
string += ' '
string += ":"
string += " {}|{}@".format(self.start_bit, self.numbits)
if self.is_little_endian:
string += '1'
else:
string += '0'
if self.is_signed:
string += '-'
else:
string += '+'
string += " ({},{})".format(self.factor, self.offset)
string += " [{}|{}]".format(self.range.minval, self.range.maxval)
string += " \"{}\" {}".format(self.unit, self.receivers[0])
for r in self.receivers[1:]:
string += ", {}".format(r)
string += "\n"
return string
def dbc_sg_mul_val(self):
strings = []
if not self.is_multiplexor:
return ''
sigs, d = self.switch.dbc_sg_mul_val_strs()
for sig in sigs:
strings.append(sig.name + ' ' + self.name + ' ' + d[sig.name])
strings += sig.dbc_sg_mul_val()
return strings
def diff(self, other):
"""Returns string descriptions of difference between signal
and other signal.
"""
self_dbc = self.dbc()
other_dbc = other.dbc()
if self_dbc != other_dbc:
return " < {} > {}".format(self.dbc(), other.dbc())
return ''
class SignalGroup(list):
"""Class of signal groups associated with a message.
"""
def __init__(self, n, *args, **kwargs):
"""Initialize signal group object.
Args:
n(int): Repetitions.
"""
super().__init__(*args, **kwargs)
self.n = n
def __str__(self):
string = "{} = ".format(self.n)
for signame in self:
string += signame
def dbc(self):
"""Return dbc string for signal group.
"""
string = "{} :".format(self.n)
for signame in self:
string += " " + signame
string += ';'
return string
def diff(self, other):
"""Return description of difference from other signal group.
"""
if set(self) != set(other):
return "< {}\n> {}".format(self.dbc(), other.dbc())
return ''
class Message():
"""Class for can-bus messages.
"""
def __init__(self, id, name, size, transmitter):
"""Initializes Message object.
Args:
id(int): Message id.
name(str): Name of message.
size(int): Number of bytes in message.
transmitter(str) Name of transmitting node.
"""
self.id = id
self.name = name
self.size = size
self.transmitters = [transmitter]
self.signals = []
self.signals_dict = {}
self.comments = []
self.attributes = {}
self.signal_groups = {}
def append(self, sg):
"""Append signal to messsage.
Args:
sg(Signal): Signal object to append.
"""
self.signals.append(sg)
self.signals_dict[sg.name] = sg
def __str__(self):
string = "{} {}, {} bytes".format(self.id, self.name, self.size)
if self.transmitters:
string += ', transmitters: ' + ' '.join(self.transmitters)
string += "\n"
for c in self.comments:
string += 4*" " + c + "\n"
if self.attributes:
string += 4*" " + "attributes=" + str(self.attributes) + "\n"
if self.signal_groups:
string += 4*" " + "signal_gropus=" + str(self.signal_groups) + "\n"
if self.signals:
sig_string = "signals:\n"
sub_sig_string = ""
for s in self.signals:
sub_sig_string += str(s) + "\n"
sig_string += textwrap.indent(sub_sig_string, 4*' ')
string += textwrap.indent(sig_string, 4*" ")
return string
def dbc(self):
"""Return dbc-statement for message.
"""
string = "BO_ {} {}: {} {}\n".format(self.id, self.name, self.size,
self.transmitters[0])
for signame in self.signals_dict:
sig = self.signals_dict[signame]
string += " " + sig.dbc()
return string
def dbc_sg_mul_val(self):
sigstr = ""
sd = self.signals_dict
multiple_muxes = len([s for s in sd if sd[s].is_multiplexor]) > 1
multiple_switches = False
for s in sd:
multiple_switches = multiple_switches\
or sd[s].switch.any_multiples()
if multiple_muxes or multiple_switches:
for s in self.signals:
sstrs = s.dbc_sg_mul_val()
for sstr in sstrs:
sigstr += "SG_MUL_VAL_ {} {};\n".format(self.id, sstr)
return sigstr
def diff(self, other):
"""Return string describing difference from other message.
"""
# id
if self.id != other.id:
return "message id:\n < {}\n > {}\n".format(self.id, other.id)
# name
if self.name != other.name:
return "id {} message name:\n < {}\n > {}\n".format(self.id,
self.name,
other.name)
# size
if self.size != other.size:
return "id {} message size:\n < {}\n > {}\n".format(self.id,
self.size,
other.size)
# transmitters = [transmitter, ...]
own_tx = set(self.transmitters)
other_tx = set(other.transmitters)
unique_own = own_tx - other_tx
unique_other = other_tx - own_tx
if unique_own or unique_other:
return "id {} transmitters :\n < {}\n > {}\n".format(
self.id, unique_own, unique_other)
# signals_dict
own_sigs = set(self.signals_dict.keys())
other_sigs = set(other.signals_dict.keys())
unique_own = own_sigs - other_sigs
unique_other = other_sigs - own_sigs
if unique_own or unique_other:
return "message id {} signals :\n < {}\n > {}\n".format(
self.id, unique_own, unique_other)
for signame in self.signals_dict:
sig_self = self.signals_dict[signame]
sig_other = other.signals_dict[signame]
string = sig_self.diff(sig_other)
if string:
return "message id {} signal {}:\n{}\n".format(self.id,
signame,
string)
# message comments
if self.comments != other.comments:
return "id {} comments:\n < {}\n > {}\n".format(
self.id, self.comments, other.comments)
# attributes
if self.attributes != other.attributes:
return "id {} attributes:\n < {}\n > {}\n".format(
self.id, self.attributes, other.attributes)
# signal_groups
own_groups = set(self.signal_groups.keys())
other_groups = set(other.signal_groups.keys())
unique_own = own_groups - other_groups
unique_other = other_groups - own_groups
if unique_own or unique_other:
return "id {} signal groups :\n < {}\n > {}\n".format(
self.id, unique_own, unique_other)
for groupname in self.signal_groups:
group_self = self.signal_groups[groupname]
group_other = other.signal_groups[groupname]
string = group_self.diff(group_other)
if string:
return "id {} signal group {} :\n {}\n".format(
self.id, groupname, string)
# done
return ''
class Bus():
"""Class containing all information on CAN-bus.
This class can hold all information that is contained in a
dbc-file.
"""
def _exception_handler(self, exception_type, exception, traceback):
if exception_type == DatabaseError:
print("{}: {}".format(exception_type.__name__, exception))
else:
self._old_excepthook(exception_type, exception, traceback)
def __init__(self, seclist0, usermode=True, debugmode=None):
"""Initializes Bus object.
Args:
seclist0(list): List of tuples containing parsed sections.
usermode(bool): If True, trace of error messages are not shown.
debugmode(bool): If True, print parsed sections as
they are processed
"""
self._usermode = usermode
if self._usermode:
self._old_excepthook = sys.excepthook
sys.excepthook = self._exception_handler
if debugmode is None:
self._debugmode = not self._usermode
else:
self._debugmode = debugmode
seclist = seclist0.copy()
# *** mandatory sections
# VERSION ('VERSION', version_string)
sl = self._xtract_sec(seclist, 'VERSION')
if len(sl) == 0:
raise DatabaseError("missing section: \"VERSION\"")
elif len(sl) > 1:
raise DatabaseError("more than one section of type \"VERSION\"")
if self._debugmode:
print(sl[0])
self.version = sl[0][1]
# BS_ ('BS_', None) | or ('BS_', (baudrate_int, btr1_int, btr2_int)
sl = self._xtract_sec(seclist, 'BS_')
if len(sl) == 0:
raise DatabaseError("missing section: \"BS_\"")
elif len(sl) > 1:
raise DatabaseError("more than one section of type \"BS_\"")
if self._debugmode:
print(sl[0])
t = sl[0]
if t[1]:
self.baudrate = t[1][0]
self.btr = t[1][1:]
else:
self.baudrate = None
self.btr = None
# BU_ ('BU_', nodenames_list)
sl = self._xtract_sec(seclist, 'BU_')
if len(sl) == 0:
raise DatabaseError("missing section: \"BU_\"")
elif len(sl) > 1:
raise DatabaseError("more than one section of type \"BU_\"")
if self._debugmode:
print(sl[0])
nl = sl[0][1]
not_unique = len(nl) - len(set(nl))
if not_unique:
warnings.warn("BU_: repeated nodes, removing duplicates",
DatabaseWarning)
nl = list(dict.fromkeys(nl))
self.nodes = {}
for node in nl:
self.nodes[node] = {'comments': [], 'attributes': {}}
# *** optional sections
# NS_ ('NS_', new_symbols_list)
sl = self._xtract_sec(seclist, 'NS_')
if len(sl) == 0:
self.newsymbols = []
elif len(sl) > 1:
raise DatabaseError("more than one section of type \"NS_\"")
else:
self.newsymbols = sl[0][1].copy()
if self._debugmode:
print(sl[0])
# VAL_TABLE_ ('VAL_TABLE_', name_string, table_list) table (int str)*
self.global_values = {}
sl = self._xtract_sec(seclist, 'VAL_TABLE_')
for tab in sl:
tabname = tab[1]
if tabname in self.global_values:
raise DatabaseError("multiply defined table \"{}\"".format(
tabname))
vals = {}
tab[2].sort(key=lambda x: x[0], reverse=True)
for t in tab[2]:
if t[0] in vals:
warnings.warn("table \"{}\" has value {} defined "
"more than once, last definition is "
"used".format(tabname, t[0]),
DatabaseWarning)
vals[t[0]] = t[1]
self.global_values[tabname] = vals
if self._debugmode:
print(tab)
# BO_ ('BO_', d_dict)
# d['id'] = message_id
# d['name'] = message_name
# d['size'] = size
# d['transmitter'] = transmitter
# d['signals'] = list_signals
ml = self._xtract_sec(seclist, 'BO_')
self.messages = {}
for _, msg_d in ml:
if self._debugmode:
print(('BO_', msg_d))
msg = Message(msg_d['id'], msg_d['name'], msg_d['size'],
msg_d['transmitter'])
if msg.id in self.messages:
raise DatabaseError("multiple definitions of "
"message {} {} ".format(msg.id, msg.name))
self.messages[msg.id] = msg
for sig_d in msg_d['signals']:
msg.append(Signal(sig_d))
# BO_TX_BU_ ('BO_TX_BU_', id_int, transmitters_list_of_identifiers)
ml = self._xtract_sec(seclist, 'BO_TX_BU_')
self.comments = []
for bo in ml:
if self._debugmode:
print(bo)
id = bo[1]
if id in self.messages:
msg = self.messages[id]
else:
raise DatabaseError("undefined message id \"{}\" in BO_TX_BU-"
"statement".format(id))
for tx in bo[2]:
if tx not in self.nodes:
raise DatabaseError("transmitter \"{}\" not among "
"defined nodes".format(tx))
if tx not in msg.transmitters:
msg.transmitters.append(tx)
# EV_ not implemented
# ENVVAR_DATA_ not implemented
# SGTYPE_ not implemented
#
# CM_ ('CM_', ('BU_', name | 'BO_', message_id
# | 'SG_', message_id, name | 'EV_', name
# | '' , comment_string))
cl = self._xtract_sec(seclist, 'CM_')
for c0 in cl:
if self._debugmode:
print(c0)
c = c0[1]
ct = c[0]
if ct == '':
self.comments.append(c[1])
elif ct == 'BU_':
name = c[1]
if name in self.nodes:
self.nodes[name]['comments'].append(c[2])
else:
raise DatabaseError("comment for undefined node \"{}\"",
name)
elif ct == 'BO_':
msg_id = c[1]
if msg_id in self.messages:
self.messages[msg_id].comments.append(c[2])
else:
raise DatabaseError("comment for undefined message \"{}\"".
format(msg_id))
elif ct == 'SG_':
msg_id = c[1]
name = c[2]
if msg_id in self.messages:
msg = self.messages[msg_id]
if name in msg.signals_dict:
msg.signals_dict[name].comments.append(c[3])
else:
raise DatabaseError("comment for undefined signal "
"\"{}\" in message \"{}\"".format(
name, msg_id))
else:
raise DatabaseError("comment for signal \"{}\" in "
"undefined message \"{}\"".format(
name, msg_id))
elif ct == 'EV_':
raise DatabaseError("CM_ EV_ not implented")
else:
raise ValueError("unknown comment type specifier "
"\"{}\"".format(ct))
# BA_DEF_ ('BA_DEF_', spec, name, typ)
# spec = 'BU_' | 'BO_' | 'SG_' | 'EV_' | '')
self.attrib_typedefs = {'': {}, 'BU_': {}, 'BO_': {},
'SG_': {}, 'EV_': {}}
cl = self._xtract_sec(seclist, 'BA_DEF_')
for c0 in cl:
if self._debugmode:
print(c0)
ct = c0[1]
name = c0[2]
typ = c0[3]
if ct not in self.attrib_typedefs:
raise DatabaseError("unknown object type \"{}\" in BA_DEF_".
format(ct))
if name in self.attrib_typedefs[ct]:
raise DatabaseError("attribute \"{}\" already defined "
"for \"{}\"".format(name, ct))
if typ[0] in ["INT", "HEX", "FLOAT"]:
self.attrib_typedefs[ct][name] = {'type': typ[0],
'values': typ[1:]}
elif typ[0] == 'STRING':
self.attrib_typedefs[ct][name] = {'type': typ[0],
'values': None}
elif typ[0] == 'ENUM':
self.attrib_typedefs[ct][name] = {'type': typ[0],
'values': typ[1]}
else:
raise ValueError("unknown object type \"{}\"".format(typ[0]))
# BA_DEF_DEF_ ('BA_DEF_DEF_', name_identifier, val)
self.attrib_defaults = {}
cl = self._xtract_sec(seclist, 'BA_DEF_DEF_')
for t, name, val in cl:
if self._debugmode:
print((t, name, val))
if name in self.attrib_defaults:
raise DatabaseError("attribute default value for \"{}\" "
"multiply defined", format(name))
self.attrib_defaults[name] = val
# BA_ ('BA_', name_identifier, desc, val)
# desc = ('BU_', nodename | 'BO_', message_id
# | 'SG_', message_id, name | 'EV_', name | '' )
self.attributes = {}
cl = self._xtract_sec(seclist, 'BA_')
for c in cl:
if self._debugmode:
print(c)
name = c[1]
d = c[2]
val = c[3]
ct = d[0]
if ct == '':
if name in self.attributes:
raise DatabaseError("general attribute \"{}\" multiply "
"defined ".format(name))
self.attributes[name] = val
elif ct == 'BU_':
node = d[1]
if node not in self.nodes:
raise DatabaseError("unknown node \"{}\" in attribute "
"value statement".format(node))
nda = self.nodes[node]['attributes']
if name in nda:
raise DatabaseError("attribute \"{}\" multiply defined "
"for node \"{}\"".format(name, node))
nda[name] = val
elif ct == 'BO_':
id = d[1]
if id not in self.messages:
raise DatabaseError("unknown message id \"{}\" in "
"attribute value statement".format(id))
msg = self.messages[id]
if name in msg.attributes:
raise DatabaseError("attribute \"{}\" multiply defined for"
" message \"{}\"".format(name, id))
msg.attributes[name] = val
elif ct == 'SG_':
id = d[1]
signame = d[2]
if id not in self.messages:
raise DatabaseError("unknown message id \"{}\" in "
"attribute value statement for "
"signal \"{}\"".format(id, sig))
sigs = self.messages[id].signals_dict
if signame not in sigs:
raise DatabaseError("unknown message - signal desgination "
"\"{}\" - \"{}\" in attribute value "
"statement".format(id, sig))
attr = sigs[signame].attributes
if name in attr:
raise DatabaseError("attribute \"{}\" multiply defined for"
" signal \"{}\" in message \"{}\"".
format(name, sig, id))
elif ct == 'EV_':
raise DatabaseError("attributes for EV_ not implemented")
else:
ValueError("unknown object identifier \"{}\" in attribute "
"statement".format(ct))
# VAL_ ('VAL_', (message_id, sig_name), vals)
cl = self._xtract_sec(seclist, 'VAL_')
for c in cl:
if self._debugmode:
print(c)
id = c[1][0]
signame = c[1][1]
if id not in self.messages:
raise DatabaseError("unknown message id \"{}\" in "
"signal value description for "
"signal \"{}\"".format(id, signame))
sigs = self.messages[id].signals_dict
if signame not in sigs:
raise DatabaseError("unknown message - signal designation "
"\"{}\" - \"{}\" in signal value "
"description".format(id, signame))
for val, desc in c[2]:
sigs[signame].value_descriptions[val] = desc
# SIG_GROUP_ ('SIG_GROUP_', msg_id, name, number, sigs)
cl = self._xtract_sec(seclist, 'SIG_GROUP_')
for c in cl:
if self._debugmode:
print(c)
id = c[1]
group_name = c[2]
if id not in self.messages:
raise DatabaseError("unknown message id \"{}\" in "
"definition of signal group \"{}\"".
format(id, group_name))
msg = self.messages[id]
if group_name in msg.signal_groups:
raise DatabaseError("signal group \"{}\" already defined for "
"message \"{}\"".format(goup_name, id))
signals = [] # preserve order but drop duplicates
for signame in c[4]:
if signame not in signals:
signals.append(signame)
undef = list(set(signals) - set(msg.signals_dict))
if undef:
errstr = "undefined signals in definition of group " +\
groupname + " for message \"{}\": ".format(id)\
+ undef[0]
for s in undef[1:]:
errstr += ', ' + s
raise DatabaseError(errstr)
msg.signal_groups[group_name] = SignalGroup(c[3], signals)
# SIG_VALTYPE_ ( 'SIG_VALTYPE_' message_id, signal_name, tn)
cl = self._xtract_sec(seclist, 'SIG_VALTYPE_')
for c in cl:
if self._debugmode:
print(c)
id = c[1]
signame = c[2]
if id not in self.messages:
raise DatabaseError("unknown message id \"{}\" in "
"signal value-type statement for "
"signal \"{}\"".format(id, signame))
sigs = self.messages[id].signals_dict
if signame not in sigs:
raise DatabaseError("unknown message - signal desgination "
"\"{}\" - \"{}\" in signal value-type "
"statement".format(id, signame))
sigs[signame].value_type = c[3]
# for messages with only one multiplexor, organize accordingly
for id in self.messages:
msg = self.messages[id]
mux = None
multiplexed = []
num_muxes = 0
for sig in msg.signals:
if sig.is_multiplexor:
num_muxes += 1
mux = sig
if sig.multiplex_value is not None:
multiplexed.append(sig)
if num_muxes == 1: # organize into hierarchy
for sig in multiplexed:
if mux.multiplexes(sig.multiplex_value):
r = Range(sig.multiplex_value, sig.multiplex_value)
mux.switch.append(r, sig)
else:
raise DatabaseError("multiplex value for signal \"{}\""
" in message \"{}\" is not in "
"range of multiplexor \"{}\"".
format(sig.name, msg.id, mux.name))
msg.signals.remove(sig)
# SG_MUL_VAL_ ('SG_MUL_VAL_', (message_id, signal_name,
# multiplexor_name), ranges)
cl = self._xtract_sec(seclist, 'SG_MUL_VAL_')
for c in cl:
if self._debugmode:
print(c)
id = c[1][0]
signame = c[1][1]
muxname = c[1][2]
ranges = c[2]
if id not in self.messages:
raise DatabaseError("unknown message id \"{}\" in "
"extended multiplexing statement for "
"signal \"{}\" and mux \"{}\" ".format(
id, signame, muxname))
msg = self.messages[id]
if signame not in msg.signals_dict:
raise DatabaseError("unknown signal name \"{}\" in "
"extended multiplexing statement for "
"message id \"{}\"".format(signame, id))
sig = msg.signals_dict[signame]
if muxname not in msg.signals_dict:
raise DatabaseError("unknown multiplexor name \"{}\" in "
"extended multiplexing statement for "
"message id \"{}\"".format(muxname, id))
mux = msg.signals_dict[muxname]
if not mux.is_multiplexor:
raise DatabaseError("named multiplexor \"{}\" in "
"extended multiplexing statement for "
"message id \"{}\" is not a multiplexor".
format(muxname, id))
if sig in msg.signals:
msg.signals.remove(sig)
for r0 in ranges:
r = Range(r0)
mux.switch.append(r, sig)
else:
raise DatabaseError("signal \"{}\" in message \"{}\" "
"multiplexed be more than one "
"multiplexor".format(signame, id))
nonmuxed = []
for id in self.messages:
msg = self.messages[id]
for sig in msg.signals:
if sig.multiplex_value is not None:
nonmuxed.append((msg, sig))
if nonmuxed: # do this for now, later maybe assign to toplevel mux
s = "there were signals with unspecified multiplexor: "
for t in nonmuxed:
s += "\n \"{}\": \"{}\"".format(t[0].id, t[1].name)
raise DatabaseError(s)
# if not everything is unpacked
if seclist:
raise Exception("sections left to unpack: "+str(seclist))
# *** final touch
if self._usermode:
sys.excepthook = self._old_excepthook
def _xtract_sec(self, seclist, sec):
indices = [kk for kk in range(len(seclist)) if seclist[kk][0] == sec]
indices.sort(reverse=True)
xtr = []
for ii in indices:
xtr.append(seclist.pop(ii))
xtr.reverse()
return xtr
########################################################################
def dbc(self):
"""Returns dbc-format representation of Bus.
"""
string = ""
# VERSION self.version
string += "VERSION " + "\"" + self.version + "\"\n\n"
# new symbols
string += "NS_ :\n"
for s in self.newsymbols:
string += " {}\n".format(s)
string += "\n"
# baudrate and timing
string += "BS_:"
if self.baudrate and self.btr:
string += " {}: {}, {}".format(self.baudrate,
self.btr[0], self.btr[1])
string += "\n\n"
# nodes
# BU_ self.nodes[node] = {'comments': [], 'attributes': {}}
string += "BU_:"
for node in self.nodes:
string += " " + node
string += "\n\n"
# VAL_TABLE_ self.global_values dict
for tab in self.global_values:
string += "VAL_TABLE_ " + tab
d = self.global_values[tab]
table = [(n, d[n]) for n in d]
table.sort(key=lambda x: x[0], reverse=True)
for t in table:
string += " {} \"{}\"".format(*t)
string += " ;\n"
if self.global_values:
string += "\n"
# messages
for msgid in self.messages:
string += self.messages[msgid].dbc()
if self.messages:
string += "\n"
# transmitter list
count = 0
for msgid in self.messages:
msg = self.messages[msgid]
if len(msg.transmitters) > 1:
count += 1
string += "BO_TX_BU_ {}:".format(msgid)
for tx in msg.transmitters:
string += " " + tx
string += " ;\n"
if count:
string += "\n"
# environment_variables environment_variables_data signal_types
# not implemented
# comments
count = 0
for c in self.comments:
count += 1
ce = c.replace("\"", "\\\"")
string += "CM_ \"{}\";\n".format(ce)
for node in self.nodes:
cl = self.nodes[node]['comments']
for c in cl:
count += 1
ce = c.replace("\"", "\\\"")
string += "CM_ BU_ {} \"{}\";\n".format(node, ce)
for msgid in self.messages:
msg = self.messages[msgid]
for c in msg.comments:
count += 1
ce = c.replace("\"", "\\\"")
string += "CM_ BO_ {} \"{}\";\n".format(msgid, ce)
d = msg.signals_dict
for signame in d:
sig = d[signame]
for c in sig.comments:
count += 1
ce = c.replace("\"", "\\\"")
string += "CM_ SG_ {} {} \"{}\";\n".format(msgid,
signame, ce)
# EV_ comments not implemented
if count:
string += "\n"
# attribute definitions
# self.attrib_typedefs = {'': {}, 'BU_': {}, 'BO_': {},
# 'SG_': {}, 'EV_': {}}
# keys 'type', 'values'
count = 0
for ot in self.attrib_typedefs:
d = self.attrib_typedefs[ot]
for attrname in d:
tdef = d[attrname]