-
-
Notifications
You must be signed in to change notification settings - Fork 557
/
dbc.py
1420 lines (1101 loc) · 42.6 KB
/
dbc.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
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
# Load and dump a CAN database in DBC format.
import re
from collections import OrderedDict as odict
from collections import defaultdict
from decimal import Decimal
import textparser
from textparser import Sequence
from textparser import choice
from textparser import ZeroOrMore
from textparser import OneOrMore
from textparser import OneOrMoreDict
from textparser import DelimitedList
from textparser import Any
from textparser import AnyUntil
from textparser import tokenize_init
from textparser import Token
from textparser import TokenizeError
from textparser import Optional
from ..attribute_definition import AttributeDefinition
from ..attribute import Attribute
from ..signal import Signal
from ..signal import Decimal as SignalDecimal
from ..message import Message
from ..node import Node
from ..bus import Bus
from ..internal_database import InternalDatabase
from ..environment_variable import EnvironmentVariable
from .utils import num
DBC_FMT = (
'VERSION "{version}"\r\n'
'\r\n'
'\r\n'
'NS_ : \r\n'
'\tNS_DESC_\r\n'
'\tCM_\r\n'
'\tBA_DEF_\r\n'
'\tBA_\r\n'
'\tVAL_\r\n'
'\tCAT_DEF_\r\n'
'\tCAT_\r\n'
'\tFILTER\r\n'
'\tBA_DEF_DEF_\r\n'
'\tEV_DATA_\r\n'
'\tENVVAR_DATA_\r\n'
'\tSGTYPE_\r\n'
'\tSGTYPE_VAL_\r\n'
'\tBA_DEF_SGTYPE_\r\n'
'\tBA_SGTYPE_\r\n'
'\tSIG_TYPE_REF_\r\n'
'\tVAL_TABLE_\r\n'
'\tSIG_GROUP_\r\n'
'\tSIG_VALTYPE_\r\n'
'\tSIGTYPE_VALTYPE_\r\n'
'\tBO_TX_BU_\r\n'
'\tBA_DEF_REL_\r\n'
'\tBA_REL_\r\n'
'\tBA_DEF_DEF_REL_\r\n'
'\tBU_SG_REL_\r\n'
'\tBU_EV_REL_\r\n'
'\tBU_BO_REL_\r\n'
'\tSG_MUL_VAL_\r\n'
'\r\n'
'BS_:\r\n'
'\r\n'
'BU_: {bu}\r\n'
'{val_table}'
'\r\n'
'\r\n'
'{bo}\r\n'
'\r\n'
'{bo_tx_bu}\r\n'
'\r\n'
'\r\n'
'{cm}\r\n'
'{signal_types}'
'{ba_def}\r\n'
'{ba_def_def}\r\n'
'{ba}\r\n'
'{val}\r\n'
'\r\n'
)
# Signal types.
SIGNAL_TYPE_FLOAT = 1
SIGNAL_TYPE_DOUBLE = 2
FLOAT_SIGNAL_TYPES = [
SIGNAL_TYPE_FLOAT,
SIGNAL_TYPE_DOUBLE
]
FLOAT_LENGTH_TO_SIGNAL_TYPE = {
32: SIGNAL_TYPE_FLOAT,
64: SIGNAL_TYPE_DOUBLE
}
def to_int(value):
return int(Decimal(value))
class Parser(textparser.Parser):
def tokenize(self, string):
keywords = set([
'BA_',
'BA_DEF_',
'BA_DEF_DEF_',
'BA_DEF_DEF_REL_',
'BA_DEF_REL_',
'BA_DEF_SGTYPE_',
'BA_REL_',
'BA_SGTYPE_',
'BO_',
'BO_TX_BU_',
'BS_',
'BU_',
'BU_BO_REL_',
'BU_EV_REL_',
'BU_SG_REL_',
'CAT_',
'CAT_DEF_',
'CM_',
'ENVVAR_DATA_',
'EV_',
'EV_DATA_',
'FILTER',
'NS_',
'NS_DESC_',
'SG_',
'SG_MUL_VAL_',
'SGTYPE_',
'SGTYPE_VAL_',
'SIG_GROUP_',
'SIG_TYPE_REF_',
'SIG_VALTYPE_',
'SIGTYPE_VALTYPE_',
'VAL_',
'VAL_TABLE_',
'VERSION'
])
names = {
'LPAREN': '(',
'RPAREN': ')',
'LBRACE': '[',
'RBRACE': ']',
'COMMA': ',',
'AT': '@',
'SCOLON': ';',
'COLON': ':',
'PIPE': '|',
'SIGN': '+/-'
}
token_specs = [
('SKIP', r'[ \r\n\t]+|//.*?\n'),
('NUMBER', r'-?\d+\.?\d*([eE][+-]?\d+)?'),
('WORD', r'[A-Za-z0-9_]+'),
('STRING', r'"(\\"|[^"])*?"'),
('LPAREN', r'\('),
('RPAREN', r'\)'),
('LBRACE', r'\['),
('RBRACE', r'\]'),
('COMMA', r','),
('PIPE', r'\|'),
('AT', r'@'),
('SIGN', r'[+-]'),
('SCOLON', r';'),
('COLON', r':'),
('MISMATCH', r'.')
]
tokens, token_regex = tokenize_init(token_specs)
for mo in re.finditer(token_regex, string, re.DOTALL):
kind = mo.lastgroup
if kind == 'SKIP':
pass
elif kind == 'STRING':
value = mo.group(kind)[1:-1].replace('\\"', '"')
tokens.append(Token(kind, value, mo.start()))
elif kind != 'MISMATCH':
value = mo.group(kind)
if value in keywords:
kind = value
if kind in names:
kind = names[kind]
tokens.append(Token(kind, value, mo.start()))
else:
raise TokenizeError(string, mo.start())
return tokens
def grammar(self):
version = Sequence('VERSION', 'STRING')
ns = Sequence('NS_', ':', AnyUntil(Sequence(Any(), ':')))
bs = Sequence('BS_', ':')
nodes = Sequence('BU_', ':', ZeroOrMore('WORD'))
signal = Sequence(
'SG_', choice(Sequence('WORD', 'WORD'), Sequence('WORD')), ':',
'NUMBER', '|', 'NUMBER', '@', 'NUMBER', '+/-',
'(', 'NUMBER', ',', 'NUMBER', ')',
'[', 'NUMBER', '|', 'NUMBER', ']',
'STRING',
DelimitedList('WORD'))
message = Sequence(
'BO_', 'NUMBER', 'WORD', ':', 'NUMBER', 'WORD', ZeroOrMore(signal))
environment_variable = Sequence(
'EV_', 'WORD', ':', 'NUMBER',
'[', 'NUMBER', '|', 'NUMBER', ']',
'STRING', 'NUMBER', 'NUMBER', 'WORD', 'WORD', ';')
comment = Sequence(
'CM_',
choice(
Sequence('SG_', 'NUMBER', 'WORD', 'STRING'),
Sequence('BO_', 'NUMBER', 'STRING'),
Sequence('EV_', 'WORD', 'STRING'),
Sequence('BU_', 'WORD', 'STRING'),
'STRING'),
';')
attribute_definition = Sequence(
'BA_DEF_',
Optional(choice('SG_', 'BO_', 'EV_', 'BU_')),
'STRING',
'WORD',
Optional(choice(DelimitedList('STRING'), ZeroOrMore('NUMBER'))),
';')
attribute_definition_default = Sequence(
'BA_DEF_DEF_', 'STRING', choice('NUMBER', 'STRING'), ';')
attribute = Sequence(
'BA_', 'STRING',
ZeroOrMore(choice(Sequence('BO_', 'NUMBER'),
Sequence('SG_', 'NUMBER', 'WORD'),
Sequence('BU_', 'WORD'),
Sequence('EV_', 'WORD'))),
choice('NUMBER', 'STRING'),
';')
attribute_definition_rel = Sequence(
'BA_DEF_REL_',
Optional('BU_SG_REL_'),
'STRING',
'WORD',
choice(DelimitedList('STRING'), OneOrMore('NUMBER')),
';')
attribute_definition_default_rel = Sequence(
'BA_DEF_DEF_REL_', 'STRING', choice('NUMBER', 'STRING'), ';')
attribute_rel = Sequence(
'BA_REL_', 'STRING', 'BU_SG_REL_', 'WORD', 'SG_', 'NUMBER',
'WORD', choice('NUMBER', 'STRING'), ';')
choice_ = Sequence(
'VAL_',
Optional('NUMBER'),
'WORD',
ZeroOrMore(Sequence('NUMBER', 'STRING')),
';')
value_table = Sequence(
'VAL_TABLE_', 'WORD', ZeroOrMore(Sequence('NUMBER', 'STRING')), ';')
signal_type = Sequence(
'SIG_VALTYPE_', 'NUMBER', 'WORD', ':', 'NUMBER', ';')
signal_multiplexer_values = Sequence(
'SG_MUL_VAL_',
'NUMBER',
'WORD',
'WORD',
DelimitedList(Sequence('NUMBER', 'NUMBER')),
';')
message_add_sender = Sequence(
'BO_TX_BU_', 'NUMBER', ':', DelimitedList('WORD'), ';')
signal_group = Sequence(
'SIG_GROUP_', 'NUMBER', 'WORD', 'NUMBER', ':', OneOrMore('WORD'), ';')
return OneOrMoreDict(
choice(
message,
comment,
attribute_definition,
value_table,
choice_,
attribute,
attribute_rel,
attribute_definition_rel,
attribute_definition_default,
attribute_definition_default_rel,
signal_group,
signal_type,
signal_multiplexer_values,
message_add_sender,
environment_variable,
nodes,
ns,
bs,
version))
class DbcSpecifics(object):
def __init__(self,
attributes=None,
attribute_definitions=None,
environment_variables=None,
value_tables=None):
self._attributes = attributes
self._attribute_definitions = attribute_definitions
self._environment_variables = environment_variables
if value_tables is None:
value_tables = odict()
self._value_tables = value_tables
@property
def attributes(self):
"""The DBC specific attributes of the parent object (database, node,
message or signal) as a dictionary.
"""
return self._attributes
@property
def attribute_definitions(self):
"""The DBC specific attribute definitions as dictionary.
"""
return self._attribute_definitions
@property
def value_tables(self):
"""An ordered dictionary of all value tables. Only valid for DBC
specifiers on database level.
"""
return self._value_tables
@property
def environment_variables(self):
"""An ordered dictionary of all environment variables. Only valid for
DBC specifiers on database level.
"""
return self._environment_variables
class LongNamesConverter(object):
def __init__(self, names):
self._long_to_short_names_dict = {}
next_index_per_base_name = {}
short_names = set()
def basename(name):
return name[:27]
for name in names:
if len(name) != 32:
continue
next_index_per_base_name[basename(name)] = 0
short_names.add(name)
for name in names:
if len(name) <= 32:
continue
base_name = basename(name)
short_name = name[:32]
if short_name in short_names:
index = next_index_per_base_name[base_name]
next_index_per_base_name[base_name] += 1
short_name = '{}_{:04d}'.format(name[:27], index)
else:
next_index_per_base_name[base_name] = 0
short_names.add(short_name)
self._long_to_short_names_dict[name] = short_name
def lookup_name(self, name):
if name in self._long_to_short_names_dict:
name = self._long_to_short_names_dict[name]
return name
@property
def long_to_short_names_dict(self):
return self._long_to_short_names_dict
def get_dbc_frame_id(message):
frame_id = message.frame_id
if message.is_extended_frame:
frame_id |= 0x80000000
return frame_id
def _get_node_name(attributes, name):
try:
return attributes['node'][name]['SystemNodeLongSymbol'].value
except (KeyError, TypeError):
return name
def _dump_nodes(database):
bu = []
for node in database.nodes:
bu.append(node.name)
return bu
def _dump_value_tables(database):
if database.dbc is None:
return []
val_table = []
for name, choices in database.dbc.value_tables.items():
choices = [
'{} "{}"'.format(number, text)
for number, text in reversed(sorted(choices.items()))
]
val_table.append('VAL_TABLE_ {} {} ;'.format(name, ' '.join(choices)))
return val_table + ['']
def _dump_messages(database):
bo = []
def format_mux(signal):
if signal.is_multiplexer:
return ' M'
elif signal.multiplexer_ids is not None:
return ' m{}'.format(signal.multiplexer_ids[0])
else:
return ''
def format_receivers(signal):
if signal.receivers:
return ' ' + ','.join(signal.receivers)
else:
return 'Vector__XXX'
def format_senders(message):
if message.senders:
return message.senders[0]
else:
return 'Vector__XXX'
for message in database.messages:
msg = []
fmt = 'BO_ {frame_id} {name}: {length} {senders}'
msg.append(fmt.format(frame_id=get_dbc_frame_id(message),
name=message.name,
length=message.length,
senders=format_senders(message)))
for signal in message.signals[::-1]:
fmt = (' SG_ {name}{mux} : {start}|{length}@{byte_order}{sign}'
' ({scale},{offset})'
' [{minimum}|{maximum}] "{unit}" {receivers}')
msg.append(fmt.format(
name=signal.name,
mux=format_mux(signal),
start=signal.start,
length=signal.length,
receivers=format_receivers(signal),
byte_order=(0 if signal.byte_order == 'big_endian' else 1),
sign=('-' if signal.is_signed else '+'),
scale=signal.scale,
offset=signal.offset,
minimum=(0 if signal.minimum is None else signal.minimum),
maximum=(0 if signal.maximum is None else signal.maximum),
unit='' if signal.unit is None else signal.unit))
bo.append('\r\n'.join(msg))
return bo
def _dump_senders(database):
bo_tx_bu = []
fmt = 'BO_TX_BU_ {frame_id} : {senders};'
for message in database.messages:
if len(message.senders) > 1:
bo_tx_bu.append(fmt.format(frame_id=get_dbc_frame_id(message),
senders=','.join(message.senders)))
return bo_tx_bu
def _dump_comments(database):
cm = []
for node in database.nodes:
if node.comment is not None:
fmt = 'CM_ BU_ {name} "{comment}";'
cm.append(fmt.format(name=node.name,
comment=node.comment.replace('"', '\\"')))
for message in database.messages:
if message.comment is not None:
fmt = 'CM_ BO_ {frame_id} "{comment}";'
cm.append(fmt.format(frame_id=get_dbc_frame_id(message),
comment=message.comment.replace('"', '\\"')))
for signal in message.signals[::-1]:
if signal.comment is not None:
fmt = 'CM_ SG_ {frame_id} {name} "{comment}";'
cm.append(fmt.format(frame_id=get_dbc_frame_id(message),
name=signal.name,
comment=signal.comment.replace('"', '\\"')))
return cm
def _dump_signal_types(database):
valtype = []
for message in database.messages:
for signal in message.signals:
if not signal.is_float:
continue
fmt = 'SIG_VALTYPE_ {} {} : {};'
valtype.append(fmt.format(message.frame_id,
signal.name,
FLOAT_LENGTH_TO_SIGNAL_TYPE[signal.length]))
return valtype
def _dump_attribute_definitions(database):
ba_def = []
if database.dbc is None:
return ba_def
definitions = database.dbc.attribute_definitions
def get_value(definition, value):
if definition.minimum is None:
value = ''
else:
value = ' {}'.format(value)
return value
def get_minimum(definition):
return get_value(definition, definition.minimum)
def get_maximum(definition):
return get_value(definition, definition.maximum)
def get_kind(definition):
return '' if definition.kind is None else definition.kind + ' '
for definition in definitions.values():
if definition.type_name == 'ENUM':
fmt = 'BA_DEF_ {kind} "{name}" {type_name} {choices};'
choices = ','.join(['"{}"'.format(choice)
for choice in definition.choices])
ba_def.append(fmt.format(kind=definition.kind,
name=definition.name,
type_name=definition.type_name,
choices=choices))
elif definition.type_name in ['INT', 'FLOAT', 'HEX']:
fmt = 'BA_DEF_ {kind} "{name}" {type_name}{minimum}{maximum};'
ba_def.append(fmt.format(kind=get_kind(definition),
name=definition.name,
type_name=definition.type_name,
minimum=get_minimum(definition),
maximum=get_maximum(definition)))
elif definition.type_name == 'STRING':
fmt = 'BA_DEF_ {kind} "{name}" {type_name} ;'
ba_def.append(fmt.format(kind=get_kind(definition),
name=definition.name,
type_name=definition.type_name))
return ba_def
def _dump_attribute_definition_defaults(database):
ba_def_def = []
if database.dbc is None:
return ba_def_def
definitions = database.dbc.attribute_definitions
for definition in definitions.values():
if definition.default_value is not None:
if definition.type_name in ["STRING", "ENUM"]:
fmt = 'BA_DEF_DEF_ "{name}" "{value}";'
else:
fmt = 'BA_DEF_DEF_ "{name}" {value};'
ba_def_def.append(fmt.format(name=definition.name,
value=definition.default_value))
return ba_def_def
def _dump_attributes(database):
ba = []
def get_value(attribute):
result = attribute.value
if attribute.definition.type_name == "STRING":
result = '"' + attribute.value + '"'
return result
if database.dbc is not None:
if database.dbc.attributes is not None:
for attribute in database.dbc.attributes.values():
fmt = 'BA_ "{name}" {value};'
ba.append(fmt.format(name=attribute.definition.name,
value=get_value(attribute)))
for node in database.nodes:
if node.dbc is not None:
if node.dbc.attributes is not None:
for attribute in node.dbc.attributes.values():
fmt = 'BA_ "{name}" {kind} {node_name} {value};'
ba.append(fmt.format(name=attribute.definition.name,
kind=attribute.definition.kind,
node_name=node.name,
value=get_value(attribute)))
for message in database.messages:
if message.dbc is not None:
if message.dbc.attributes is not None:
for attribute in message.dbc.attributes.values():
fmt = 'BA_ "{name}" {kind} {frame_id} {value};'
ba.append(fmt.format(name=attribute.definition.name,
kind=attribute.definition.kind,
frame_id=get_dbc_frame_id(message),
value=get_value(attribute)))
for signal in message.signals[::-1]:
if signal.dbc is not None:
if signal.dbc.attributes is not None:
for attribute in signal.dbc.attributes.values():
fmt = 'BA_ "{name}" {kind} {frame_id} {signal_name} {value};'
ba.append(fmt.format(name=attribute.definition.name,
kind=attribute.definition.kind,
frame_id=get_dbc_frame_id(message),
signal_name=signal.name,
value=get_value(attribute)))
return ba
def _dump_choices(database):
val = []
for message in database.messages:
for signal in message.signals[::-1]:
if signal.choices is None:
continue
fmt = 'VAL_ {frame_id} {name} {choices} ;'
val.append(fmt.format(
frame_id=get_dbc_frame_id(message),
name=signal.name,
choices=' '.join(['{value} "{text}"'.format(value=value,
text=text)
for value, text in signal.choices.items()])))
return val
def _load_comments(tokens):
comments = defaultdict(dict)
for comment in tokens.get('CM_', []):
if not isinstance(comment[1], list):
continue
item = comment[1]
kind = item[0]
if kind == 'SG_':
frame_id = int(item[1])
if 'signal' not in comments[frame_id]:
comments[frame_id]['signal'] = {}
comments[frame_id]['signal'][item[2]] = item[3]
elif kind == 'BO_':
frame_id = int(item[1])
comments[frame_id]['message'] = item[2]
elif kind == 'BU_':
node_name = item[1]
comments[node_name] = item[2]
elif kind == 'EV_':
environment_variable_name = item[1]
comments[environment_variable_name] = item[2]
return comments
def _load_attribute_definitions(tokens):
return tokens.get('BA_DEF_', [])
def _load_attribute_definition_defaults(tokens):
defaults = odict()
for default_attr in tokens.get('BA_DEF_DEF_', []):
defaults[default_attr[1]] = default_attr[2]
return defaults
def _load_attributes(tokens, definitions):
attributes = odict()
attributes['node'] = odict()
def to_object(attribute):
value = attribute[3]
definition = definitions[attribute[1]]
if definition.type_name in ['INT', 'HEX', 'ENUM']:
value = to_int(value)
elif definition.type_name == 'FLOAT':
value = Decimal(value)
return Attribute(value=value,
definition=definition)
for attribute in tokens.get('BA_', []):
name = attribute[1]
if len(attribute[2]) > 0:
item = attribute[2][0]
kind = item[0]
if kind == 'SG_':
frame_id_dbc = int(item[1])
signal = item[2]
if frame_id_dbc not in attributes:
attributes[frame_id_dbc] = {}
attributes[frame_id_dbc]['message'] = odict()
if 'signal' not in attributes[frame_id_dbc]:
attributes[frame_id_dbc]['signal'] = odict()
if signal not in attributes[frame_id_dbc]['signal']:
attributes[frame_id_dbc]['signal'][signal] = odict()
attributes[frame_id_dbc]['signal'][signal][name] = to_object(attribute)
elif kind == 'BO_':
frame_id_dbc = int(item[1])
if frame_id_dbc not in attributes:
attributes[frame_id_dbc] = {}
attributes[frame_id_dbc]['message'] = odict()
attributes[frame_id_dbc]['message'][name] = to_object(attribute)
elif kind == 'BU_':
node = item[1]
if node not in attributes['node']:
attributes['node'][node] = odict()
attributes['node'][node][name] = to_object(attribute)
else:
if 'database' not in attributes:
attributes['database'] = odict()
attributes['database'][name] = to_object(attribute)
return attributes
def _load_value_tables(tokens):
"""Load value tables, that is, choice definitions.
"""
value_tables = odict()
for value_table in tokens.get('VAL_TABLE_', []):
name = value_table[1]
choices = {int(number): text for number, text in value_table[2]}
value_tables[name] = choices
return value_tables
def _load_environment_variables(tokens, comments):
environment_variables = odict()
for env_var in tokens.get('EV_', []):
name = env_var[1]
environment_variables[name] = EnvironmentVariable(
name=name,
env_type=int(env_var[3]),
minimum=num(env_var[5]),
maximum=num(env_var[7]),
unit=env_var[9],
initial_value=num(env_var[10]),
env_id=int(env_var[11]),
access_type=env_var[12],
access_node=env_var[13],
comment=comments.get(env_var[1], None))
return environment_variables
def _load_choices(tokens):
choices = defaultdict(dict)
for choice in tokens.get('VAL_', []):
if len(choice[1]) == 0:
continue
od = odict((int(''.join(v[0])), v[1]) for v in choice[3])
if len(od) == 0:
continue
frame_id = int(choice[1][0])
choices[frame_id][choice[2]] = od
return choices
def _load_message_senders(tokens, attributes):
"""Load additional message senders.
"""
message_senders = defaultdict(list)
for senders in tokens.get('BO_TX_BU_', []):
frame_id = int(senders[1])
message_senders[frame_id] += [
_get_node_name(attributes, sender) for sender in senders[3]
]
return message_senders
def _load_signal_types(tokens):
"""Load signal types.
"""
signal_types = defaultdict(dict)
for signal_type in tokens.get('SIG_VALTYPE_', []):
frame_id = int(signal_type[1])
signal_name = signal_type[2]
signal_types[frame_id][signal_name] = int(signal_type[4])
return signal_types
def _load_signal_multiplexer_values(tokens):
"""Load additional signal multiplexer values.
"""
signal_multiplexer_values = defaultdict(dict)
for signal_multiplexer_value in tokens.get('SG_MUL_VAL_', []):
frame_id = int(signal_multiplexer_value[1])
signal_name = signal_multiplexer_value[2]
multiplexer_signal = signal_multiplexer_value[3]
multiplexer_ids = []
for lower, upper in signal_multiplexer_value[4]:
lower = int(lower)
upper = int(upper[1:])
# ToDo: Probably store ranges as tuples to not run out of
# memory on huge ranges.
multiplexer_ids.extend(range(lower, upper + 1))
if multiplexer_signal not in signal_multiplexer_values[frame_id]:
signal_multiplexer_values[frame_id][multiplexer_signal] = {}
multiplexer_signal = signal_multiplexer_values[frame_id][multiplexer_signal]
multiplexer_signal[signal_name] = multiplexer_ids
return signal_multiplexer_values
def _load_signals(tokens,
comments,
attributes,
definitions,
choices,
signal_types,
signal_multiplexer_values,
frame_id_dbc,
multiplexer_signal):
signal_to_multiplexer = {}
try:
signal_multiplexer_values = signal_multiplexer_values[frame_id_dbc]
for multiplexer_name, items in signal_multiplexer_values.items():
for name in items:
signal_to_multiplexer[name] = multiplexer_name
except KeyError:
pass
def get_attributes(frame_id_dbc, signal):
"""Get attributes for given signal.
"""
try:
return attributes[frame_id_dbc]['signal'][signal]
except KeyError:
return None
def get_comment(frame_id_dbc, signal):
"""Get comment for given signal.
"""
try:
return comments[frame_id_dbc]['signal'][signal]
except:
return None
def get_choices(frame_id_dbc, signal):
"""Get choices for given signal.
"""
try:
return choices[frame_id_dbc][signal]
except KeyError:
return None
def get_is_multiplexer(signal):
if len(signal[1]) == 2:
return signal[1][1].endswith('M')
else:
return False
def get_multiplexer_ids(signal, multiplexer_signal):
ids = []
if multiplexer_signal is not None:
if len(signal) == 2 and not signal[1].endswith('M'):
value = signal[1][1:].rstrip('M')
ids.append(int(value))
else:
multiplexer_signal = get_multiplexer_signal(signal,
multiplexer_signal)
try:
ids.extend(
signal_multiplexer_values[multiplexer_signal][signal[0]])
except KeyError: