-
Notifications
You must be signed in to change notification settings - Fork 0
/
oleomgr.py
1260 lines (997 loc) · 44.6 KB
/
oleomgr.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
from typing import OrderedDict
import yaml, sys, math, cantools, pprint, copy, traceback, csv
from cantools.database.can.signal import NamedSignalValue
from os import listdir
from os.path import isfile, join
'''
OpenLEO database and CAN message generation scripts
Copyright (c) 2022 - OpenLEO.org / lorddevereux
- Import DBC
- Import/Export yaml message definitions
- Export C code
- Import/merge message and signal translations
- Export database information for manual use
'''
class oleomgr:
configuration = {}
TAB = " "
TAB2 = " "
TAB3 = " "
TAB4 = " "
MODE_OLEO = 1 # 1.7 1.6 1.5
MODE_CANT = 2 # 1.0 1.1 1.2
def __init__(self, owner, config):
self.messages = OrderedDict()
if config is not None:
self.configuration = config
for i in range(self.configuration["tab_space_num"]):
self.TAB = self.TAB + " "
self.TAB2 = self.TAB + self.TAB
self.TAB3 = self.TAB2 + self.TAB
self.TAB4 = self.TAB2 + self.TAB2
self.owner = owner
self.vehicle_networks = {}
def log(self, hdr, msg = None):
if self.owner is not None:
if msg is None:
msg = hdr
hdr = "OMG"
self.owner.log(hdr, msg)
else:
print(hdr, msg)
def to_hex(self, raw_val, lng=3):
return "{0:0{1}x}".format(raw_val, lng).upper()
def dget(self, dic, key, default = 0):
'''
Safely get a given key from a dictionary
or else return a default value
'''
if type(dic) is not dict:
return default
if key in dic:
return dic[key]
else:
return default
def bitmask(self, bit, length = 1, lng = 8):
'''
Generate a bitmask for a bit at position bit
'''
out = "0b"
end = bit + (length - 1)
for i in range(lng):
if i >= bit and i <= end:
out = out + "1"
else:
out = out + "0"
return out
def endian_translate(self, start):
'''
Convert from the strange bit numbering (endian-ified)
to something we can use in code
'''
start_byte = math.ceil((start + 1) / 8)
start_bit = start % 8
return ((start_byte - 1) * 8) + (7-start_bit)
def yml_bits_encode(self, signal: cantools.database.can.Signal, output_mode=1):
'''
Convert DBC start + length to OpenLEO byte.bit format
1.7 1.6 1.5 1.4 1.3 1.2 1.1 1.0 2.7 2.6 2.5
'''
# the start position is actually the left most bit
# + 1 so the division works properly with non zero indexed bytes
start_byte = math.ceil((signal.start + 1) / 8)
start_bit = signal.start % 8
if signal.length == 1:
if output_mode == self.MODE_OLEO:
return str(start_byte) + "." + str(start_bit)
elif output_mode == self.MODE_CANT:
return str(start_byte) + "." + str(7 - start_bit)
this_bit = start_bit
this_byte = start_byte
length_left = signal.length - 1
while (length_left > 0):
this_bit -= 1
if this_bit == -1:
this_byte += 1
this_bit = 7
length_left -= 1
if output_mode == self.MODE_OLEO:
return str(start_byte) + "." + str(start_bit) + "-" + str(this_byte) + "." + str(this_bit)
elif output_mode == self.MODE_CANT:
return str(start_byte) + "." + str(7 - start_bit) + "-" + str(this_byte) + "." + str(7 - this_bit)
def yml_bits_decode(self, bits_str, input_mode = 1):
'''
Invert the operation above
'''
bit_start = 0
bit_length = 0
if "-" in bits_str:
try:
start_pos, end_pos = bits_str.split("-")
start_byte, start_bit = start_pos.split(".")
end_byte, end_bit = end_pos.split(".")
start_byte = int(start_byte)
end_byte = int(end_byte)
start_bit = int(start_bit)
end_bit = int(end_bit)
if input_mode == self.MODE_CANT:
start_bit = 7 - start_bit
end_bit = 7 - end_bit
except:
self.log("Error splitting yml_bits - " + str(bits_str))
self.log("DMP", str(traceback.format_exc()))
return False
start_byte = int(start_byte)
end_byte = int(end_byte)
start_bit = int(start_bit)
end_bit = int(end_bit)
bit_start = ((start_byte - 1) * 8) + (start_bit)
this_byte = start_byte
this_bit = start_bit
length_so_far = 1
while not (this_byte == end_byte and this_bit == end_bit):
this_bit -= 1
if this_bit == -1:
this_byte += 1
this_bit = 7
length_so_far += 1
if (this_byte > 8):
self.log("Error calculating length for yml_bits " + str(bits_str))
return False
bit_length = length_so_far
else:
start_byte, start_bit = bits_str.split(".")
start_byte = int(start_byte)
start_bit = int(start_bit)
if input_mode == self.MODE_CANT:
start_bit = 7 - start_bit
bit_start = ((start_byte - 1) * 8) + (start_bit)
bit_length = 1
return bit_start, bit_length
def yml_comment_encode(self, signal, src = None):
'''
Extract a string to a comment dict
'''
output = {}
if type(signal) is dict:
if src is not None:
signal["src"] = src
output = signal
#if "alt_name" not in output:
# output["alt_name"] = ""
if "en" not in output:
output["en"] = ""
if "fr" not in output:
output["fr"] = ""
if "src" not in output:
output["src"] = ""
return output
if signal is None:
if src is not None:
output["src"] = src
try:
if ";" in signal:
comments = signal.split(";")
for comment in comments:
csplit = comment.split("=")
output[csplit[0]] = csplit[1]
if src is not None:
output["src"] = src
else:
output["fr"] = signal
except:
pass
#if "alt_name" not in output:
# output["alt_name"] = ""
if "en" not in output:
output["en"] = ""
if "fr" not in output:
output["fr"] = ""
if "src" not in output:
output["src"] = ""
return output
def yml_comment_decode(self, comment):
out = ""
if type(comment) is str or comment is None:
return comment
else:
for key in comment:
if "comment_" in key:
key_new = key.replace("comment_", "")
else:
key_new = key
out = out + key_new + "=" + comment[key] + ";"
return out[:-1]
def txt_choices_encode(self, choices):
'''
Choices is a cantools choices object
'''
out = ""
if choices == None:
return ""
return str(choices)
def clean(self):
'''
Clear the internal db
'''
self.messages = OrderedDict()
def get_comment(self, comment, lang):
db = self.yml_comment_encode(comment)
if type(db) is dict:
if lang in db:
return db[lang]
return ""
def import_from_dbc(self, fname):
'''
Import DBC
'''
db = None
try:
db = cantools.database.load_file(fname, encoding = 'utf-8')
except:
self.log("Failed in strict mode - trying tolerant mode")
try:
db = cantools.database.load_file(fname, strict=False, encoding = 'utf-8')
except:
self.log("Failed in normal mode - check the file and try again")
self.log("DMP", str(traceback.format_exc()))
return False
self.log("Loaded " + str(len(db.messages)) + " messages")
added = 0
for message in db.messages:
if message.frame_id not in self.messages:
print(message.frame_id, type(message.frame_id))
added += 1
self.messages[message.frame_id] = message
self.log("Actually added " + str(added) + " messages")
self.check_message_structure()
return True
def export_to_dbc(self, fname, include_list):
'''
Export messages as DBC database to fname
filter messages/signals as given by chosen
'''
messages_export = []
ctr = 0
fname = str(fname)
try:
if fname.split(".")[-1] != "dbc":
fname = fname + ".dbc"
except:
fname = fname + ".dbc"
for mid in self.messages:
message = self.messages[mid]
if message.frame_id not in include_list:
ctr += 1
continue
signal_export = []
signal_offset = 0
for signal in message.signals:
if type(include_list[message.frame_id]) == list:
if signal_offset in include_list[message.frame_id]:
signal_export.append(signal)
else:
signal_export.append(signal)
signal_offset += 1
messages_export.append(message)
messages_export[-1].signals = signal_export
db = cantools.database.can.Database(messages = messages_export, strict=False)
# todo - check endianness, update is_signed and is_decimal from datatype
cantools.database.dump_file(db, fname, 'dbc', encoding = 'utf-8')
return True
def check_message_structure(self):
'''
Do standard checks on the database after import to make sure it conforms to spec
# re-order to sort by frame ID
# force all signal choices to be NamedSignalValue
'''
self.messages = OrderedDict(sorted(self.messages.items()))
for message in self.messages:
for signal in self.messages[message].signals:
if signal.choices != None:
for choice in signal.choices:
if type(signal.choices[choice]) != NamedSignalValue:
signal.choices[choice] = NamedSignalValue(choice, signal.choices[choice], "")
def export_all_signals(self, fname, include_list, comment_src = None, callback = None):
'''
Export all selected signals to CSV
'''
ctr = 0
csvfile = open(fname, 'w', newline='')
writer = csv.writer(csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
row = []
for mid in self.messages:
message = self.messages[mid]
yaml_tree = {}
if message.frame_id not in include_list:
ctr += 1
continue
receivers = []
signal_offset = 0
for signal in message.signals:
if include_list is not None:
if message.frame_id not in include_list:
continue
else:
if type(include_list[message.frame_id]) == list:
if signal_offset not in include_list[message.frame_id]:
continue
signal_offset += 1
row.append(self.to_hex(message.frame_id))
row.append(message.name)
row.append(",".join(message.senders))
row.append(signal.name)
row.append(self.yml_comment_encode(signal.comment)["name_en"])
row.append(self.yml_comment_encode(signal.comment)["comment_en"])
writer.writerow(row)
row = []
ctr += 1
csvfile.close()
return True
def export_to_yaml_oleo(self, fname, include_list, comment_src = None, callback = None):
'''
Export from internal cantools data structure
to YAML file format
'''
mode = 0
if type(include_list) == int:
# fname is a full file path
# if a given message ID is set to 1 instead of a list, it will
# export every signal in the message
include_list = { include_list : 1 }
mode = 0
fname = str(fname)
try:
if fname.split(".")[-1] != "yml":
fname = fname + ".yml"
except:
fname = fname + ".yml"
else:
# fname is a FOLDER path
mode = 1
ctr = 1
for mid in self.messages:
message = self.messages[mid]
yaml_tree = {}
if message.frame_id not in include_list:
ctr += 1
continue
receivers = []
yaml_tree[message.frame_id] = {
"id": "0x" + self.to_hex(message.frame_id),
"name": message.name,
"length": message.length,
"type": message.mtype,
"comment": self.yml_comment_encode(message.comment, comment_src),
"periodicity": message.cycle_time,
"senders": message.senders,
"signals": {}
}
id = message.frame_id
signal_offset = 0
for signal in message.signals:
if include_list is not None:
if message.frame_id not in include_list:
continue
else:
if type(include_list[message.frame_id]) == list:
if signal_offset not in include_list[message.frame_id]:
continue
signal_offset += 1
choices_clean = None
if signal.choices is not None:
choices_clean = {}
for choice in signal.choices:
comment_enc = {}
comment_enc["comment"] = self.yml_comment_encode(signal.choices[choice].comments)
comment_enc["name"] = str(signal.choices[choice])
choices_clean[choice] = comment_enc
yaml_tree[id]["signals"][signal.name] = {
"bits": self.yml_bits_encode(signal),
#"byte_order": 'big_endian',
"type": signal.dtype,
"comment": self.yml_comment_encode(signal.comment),
"min": signal.minimum,
"max": signal.maximum,
"factor": signal.scale,
"offset": signal.offset,
"units": signal.unit,
"values": choices_clean
}
# add only if relevant to the signal type
if "bool" in signal.dtype:
yaml_tree[id]["signals"][signal.name]["inverted"] = signal.inverted
# cantools uses receivers by signal, rather than
# by frame
for receiver in signal.receivers:
if receiver not in receivers:
receivers.append(receiver)
yaml_tree[id]["receivers"] = receivers
#pprint.pprint(yaml.dump(yaml_tree[0xF6]))
if mode == 0:
f = open(fname, "w")
self.log("Exporting yaml " + str(self.to_hex(message.frame_id)))
yaml.dump(yaml_tree[message.frame_id], f)
f.close()
return True
else:
self.log("Exporting yaml " + str(self.to_hex(message.frame_id)))
f = open(fname + "/" + self.to_hex(message.frame_id) + ".yml", "w")
yaml.dump(yaml_tree[message.frame_id], f)
f.close()
if callback is not None:
callback(ctr)
ctr += 1
return True
def export_to_yaml(self, fname, include_list, comment_src = None, callback = None):
'''
Export from internal cantools data structure
to YAML file format
'''
mode = 0
if type(include_list) == int:
# fname is a full file path
# if a given message ID is set to 1 instead of a list, it will
# export every signal in the message
include_list = { include_list : 1 }
mode = 0
fname = str(fname)
try:
if fname.split(".")[-1] != "yml":
fname = fname + ".yml"
except:
fname = fname + ".yml"
else:
# fname is a FOLDER path
mode = 1
ctr = 1
for mid in self.messages:
message = self.messages[mid]
yaml_tree = {}
if message.frame_id not in include_list:
ctr += 1
continue
receivers = []
yaml_tree[message.frame_id] = {
"id": "0x" + self.to_hex(message.frame_id),
"name": message.name,
"length": message.length,
"type": "can",
"comment": self.yml_comment_encode(message.comment, comment_src),
"periodicity": message.cycle_time,
"senders": message.senders,
"signals": {}
}
id = message.frame_id
signal_offset = 0
for signal in message.signals:
if include_list is not None:
if message.frame_id not in include_list:
continue
else:
if type(include_list[message.frame_id]) == list:
if signal_offset not in include_list[message.frame_id]:
continue
signal_offset += 1
choices_clean = None
if signal.choices is not None:
choices_clean = {}
for choice in signal.choices:
comment_enc = {}
comment_enc["comment"] = self.yml_comment_encode(signal.choices[choice].comments)
comment_enc["name"] = str(signal.choices[choice])
choices_clean[choice] = comment_enc
yaml_tree[id]["signals"][signal.name] = {
"bits": self.yml_bits_encode(signal),
#"byte_order": 'big_endian',
"is_signed": signal.is_signed,
"comment": self.yml_comment_encode(signal.comment),
"min": signal.minimum,
"max": signal.maximum,
"factor": signal.scale,
"offset": signal.offset,
"units": signal.unit,
"values": choices_clean
}
# cantools uses receivers by signal, rather than
# by frame
for receiver in signal.receivers:
if receiver not in receivers:
receivers.append(receiver)
yaml_tree[id]["receivers"] = receivers
#pprint.pprint(yaml.dump(yaml_tree[0xF6]))
if mode == 0:
f = open(fname, "w")
self.log("Exporting yaml " + str(self.to_hex(message.frame_id)))
yaml.dump(yaml_tree[message.frame_id], f)
f.close()
return True
else:
self.log("Exporting yaml " + str(self.to_hex(message.frame_id)))
f = open(fname + "/" + self.to_hex(message.frame_id) + ".yml", "w")
yaml.dump(yaml_tree[message.frame_id], f)
f.close()
if callback is not None:
callback(ctr)
ctr += 1
return True
def load_vehicle_def(self, fname):
'''
Load a vehicle description file
WIP - only "IS" network supported currently
'''
try:
f = open(fname)
f_contents = f.readlines()
f_contents = "".join(f_contents)
veh = yaml.safe_load(f_contents)
if "networks" in veh:
for network in veh["networks"]:
if network not in veh:
return False
else:
self.vehicle_networks[network] = []
for msg in veh[network]:
self.vehicle_networks[network].append(msg)
self.log("Successfully loaded vehicle file " + str(fname))
return True
except:
self.log("Failed loading vehicle file " + str(fname))
self.log("DMP", str(traceback.format_exc()))
return False
def import_from_yaml_oleo(self, file_list, callback = None):
'''
Import from oleo YAML to internal cantools data structure
'''
tree = {}
ctr = 1
for file_name in file_list:
try:
#if self.owner.configuration["debug"] == 1:
# self.log("Opening " + str(file_name))
f = open(file_name)
f_contents = f.readlines()
f_contents = "".join(f_contents)
msg = yaml.safe_load(f_contents)
except:
msg = None
self.log("DMP", str(traceback.format_exc()))
msg_signals = []
if msg is None:
self.log("Failed to load " + str(file_name))
continue
if "signals" not in msg:
self.log("Missing SIGNAL definitions for message " + str(file_name))
for signal in msg["signals"]:
if self.owner.configuration["debug"] == 1:
print(signal)
result = self.yml_bits_decode(msg["signals"][signal]["bits"])
if not result:
continue
bit_start, bit_length = result
# decode comment fields of choices
choices = self.dget(msg["signals"][signal], "values", {})
choices_loaded = {}
if choices is not None:
for choice in choices:
if type(choices[choice]) == dict:
# new format
if "comment" in choices[choice] and "name" in choices[choice]:
choices_loaded[choice] = NamedSignalValue(value=choice, name=choices[choice]["name"], comments=self.yml_comment_decode(choices[choice]["comment"]))
#print("New: ", choices[choice]["name"])
# legacy format
elif "en" in choices[choice]:
choices_loaded[choice] = NamedSignalValue(value=choice, name=choices[choice]["en"], comments=self.yml_comment_decode(choices[choice]))
#print("Old: ", choices[choice["en"]])
else:
pass
#print("SHOULDNT GET HERE, INVALID FILES")
else:
choices_loaded[choice] = NamedSignalValue(value=choice, name=choices[choice])
#print("Other type ", type(choice))
stype = self.dget(msg["signals"][signal], "type", "uint")
is_signed = False
is_decimal = False
if stype == "uint":
is_signed = False
is_decimal = False
if stype == "sint":
is_signed = True
is_decimal = False
if stype == "float" or stype == "double":
is_signed = True
is_decimal = True
if "is_signed" in msg["signals"][signal]:
if msg["signals"][signal]["is_signed"]:
stype = "sint"
msg_signals.append(
cantools.database.can.Signal(
name = signal,
byte_order = self.dget(msg["signals"][signal], "endian", "big_endian"),
start = bit_start,
length = bit_length,
scale = self.dget(msg["signals"][signal], "factor", 1),
offset = self.dget(msg["signals"][signal], "offset", 0),
is_signed = is_signed,
is_float = is_decimal,
dtype = stype,
inverted = self.dget(msg["signals"][signal], "inverted", False),
minimum = self.dget(msg["signals"][signal], "min", None),
maximum = self.dget(msg["signals"][signal], "max", None),
unit = self.dget(msg["signals"][signal], "units", ""),
choices = choices_loaded,
receivers = self.dget(msg, "receivers", None),
comment = self.yml_comment_decode(self.dget(msg["signals"][signal], "comment", ""))
)
)
frame_id = msg["id"]
if type(frame_id) is not int:
frame_id = int(frame_id, 16)
periodicity = self.dget(msg, "periodicity", None)
if type(periodicity) == str:
periodicity.replace("ms", "")
tree[frame_id] = cantools.database.can.Message(
strict = False,
frame_id = frame_id,
is_extended_frame = False,
name = msg["name"],
length = self.dget(msg, "length", 8),
signals = msg_signals,
mtype = self.dget(msg, "type", "can"),
comment = self.yml_comment_decode(self.dget(msg, "comment", "")),
senders = self.dget(msg, "senders", 8),
cycle_time = periodicity
)
if callback is not None:
callback(ctr)
ctr += 1
self.ignored_messages = 0
self.added_messages = 0
for message in tree:
if message not in self.messages:
self.added_messages += 1
self.messages[message] = tree[message]
else:
self.ignored_messages += 1
self.log("Imported " + str(self.added_messages) + " messages, " + str(self.ignored_messages) + " messages already exist and were skipped")
if len(self.messages) > 0:
self.check_message_structure()
return True
else:
self.log("No messages loaded")
return False
def import_from_yaml(self, file_list, callback = None):
'''
Import from YAML to internal cantools data structure
'''
tree = {}
ctr = 1
try:
for file_name in file_list:
try:
self.log("Opening " + str(file_name))
f = open(file_name)
f_contents = f.readlines()
f_contents = "".join(f_contents)
msg = yaml.safe_load(f_contents)
except:
msg = None
self.log("DMP", str(traceback.format_exc()))
msg_signals = []
if msg is None:
self.log("Failed to load " + str(file_name))
continue
if "signals" not in msg:
self.log("Missing SIGNAL definitions for message " + str(file_name))
for signal in msg["signals"]:
print(signal)
result = self.yml_bits_decode(msg["signals"][signal]["bits"])
if not result:
continue
bit_start, bit_length = result
# decode comment fields of choices
choices = self.dget(msg["signals"][signal], "values", {})
choices_loaded = {}
if choices is not None:
for choice in choices:
if type(choices[choice]) == dict:
# new format
if "comment" in choices[choice] and "name" in choices[choice]:
choices_loaded[choice] = NamedSignalValue(value=choice, name=choices[choice]["name"], comments=self.yml_comment_decode(choices[choice]["comment"]))
# legacy format
if "en" in choices[choice]:
choices_loaded[choice] = NamedSignalValue(value=choice, name=choices[choice]["en"], comments=self.yml_comment_decode(choices[choice]))
else:
choices_loaded[choice] = choices[choice]
msg_signals.append(
cantools.database.can.Signal(
name = signal,
byte_order = self.dget(msg["signals"][signal], "endian", "big_endian"),
start = bit_start,
length = bit_length,
scale = self.dget(msg["signals"][signal], "factor", 1),
offset = self.dget(msg["signals"][signal], "offset", 0),
is_signed = self.dget(msg["signals"][signal], "is_signed", 0),
minimum = self.dget(msg["signals"][signal], "min", None),
maximum = self.dget(msg["signals"][signal], "max", None),
unit = self.dget(msg["signals"][signal], "units", ""),
choices = choices_loaded,
receivers = self.dget(msg, "receivers", None),
comment = self.yml_comment_decode(self.dget(msg["signals"][signal], "comment", ""))
)
)
frame_id = msg["id"]
if type(frame_id) is not int:
frame_id = int(frame_id, 16)
tree[frame_id] = cantools.database.can.Message(
strict = False,
frame_id = frame_id,
is_extended_frame = False,
name = msg["name"],
length = self.dget(msg, "length", 8),
signals = msg_signals,
comment = self.yml_comment_decode(self.dget(msg, "comment", "")),
senders = self.dget(msg, "senders", 8),
cycle_time = self.dget(msg, "periodicity", None)
)
if callback is not None:
callback(ctr)
ctr += 1
self.ignored_messages = 0
self.added_messages = 0
for message in tree:
if message not in self.messages:
self.added_messages += 1
self.messages[message] = tree[message]
else:
self.ignored_messages += 1
self.log("Imported " + str(self.added_messages) + " messages, " + str(self.ignored_messages) + " messages already exist and were skipped")
if len(self.messages) > 0:
self.check_message_structure()
return True
else:
self.log("No messages loaded")
return False
except:
self.log("DMP", traceback.format_exc())
return False
def merge_names_to_existing_yaml(self, base_tree_fldr, trans_tree_fldr, out_fldr):
'''
This will copy comments and name fields from trans_tree to base_tree
Used when bugs are found which have damaged data in base_tree
'''
file_list = [(base_tree_fldr + "/" + f) for f in listdir(base_tree_fldr) if isfile(join(base_tree_fldr, f))]
rslt = self.import_from_yaml(file_list)
base = copy.deepcopy(self.messages)
self.messages = {}
file_list = [(trans_tree_fldr + "/" + f) for f in listdir(trans_tree_fldr) if isfile(join(trans_tree_fldr, f))]
rslt = self.import_from_yaml(file_list)
trans = copy.deepcopy(self.messages)
self.messages = {}
for msg in base:
if msg not in trans:
self.log("Message " + str(msg) + " missing from trans tree")
continue
base[msg].name = trans[msg].name
base[msg].comment = trans[msg].comment
if base[msg].signals == None:
self.log("Message " + str(msg) + " no signals")
continue
if len(base[msg].signals) != len(trans[msg].signals):
self.log("Message " + str(msg) + " signals count mismatch")
continue
sid = 0
for signal in base[msg].signals:
base[msg].signals[sid].name = trans[msg].signals[sid].name
base[msg].signals[sid].comment = trans[msg].signals[sid].comment
sid += 1
self.messages = base
inc_list = {}
for key in base.keys():
inc_list[key] = 1
rslt = self.export_to_yaml(out_fldr, inc_list)
self.log("Write result: " + str(rslt))
def export_to_struct(self, fname, include_list):
'''