-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy patheds2vhdl.py
2266 lines (2182 loc) · 99 KB
/
eds2vhdl.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
#!/usr/bin/python
"""Generates a VHDL entity from CiA306-1 compliant EDS file
Run eds2vhdl.py -h for usage
"""
import argparse
from configparser import ConfigParser
import math
import re
from sys import argv
parser = argparse.ArgumentParser()
parser.add_argument("eds", type=str, help="EDS file")
parser.add_argument("--sync", nargs="?", const=True, default=False, type=bool, help="Adds output signal for single-clock pulse when SYNC is received")
parser.add_argument("--gfc", nargs="?", const=True, default=False, type=bool, help="Adds output signal for single-clock pulse when GFC is received")
parser.add_argument("--timestamp", nargs="?", const=True, default=False, type=bool, help="Adds output signal for TIME object")
parser.add_argument("--port", nargs="+", action="extend", type=lambda x: int(x, 0), default=[], help="Object dictionary multiplexers to expose as in ports (0x101804, e.g.)")
args = parser.parse_args()
def format_constant(name, **kwargs):
name = name.upper()
name = name.replace(" ", "_")
name = re.sub(r"\b-\b", "_", name) # Replace hyphenated words with underscore
name = re.sub(r"[^\w]", "", name) # Remove illegal characters
name = re.sub(r"_{1,}", "_", name) # Remove multiple underscores
if re.match(r"[\d_]", name) is not None:
raise ValueException("Invalid object name '" + name + "'. Must start with a letter.")
if "prefix" in kwargs:
prefix = kwargs["prefix"]
else:
prefix = "\\"
if "suffix" in kwargs:
suffix = kwargs["suffix"]
else:
suffix = "\\"
return prefix + name + suffix
def make_object_from_data_type(odi):
odi = int(odi, 0)
o = {}
if odi == 0x0001: # BOOLEAN
o["bit_length"] = 1
o["data_type"] = "std_logic"
elif odi in [
0x0002, # INTEGER8
0x0003, # INTEGER16
0x0004, # INTEGER32
]:
o["bit_length"] = 2 ** (odi + 1)
o["data_type"] = "signed({:d} downto 0)".format(o.get("bit_length") - 1)
elif odi in [
0x0005, # UNSIGNED8
0x0006, # UNSIGNED16
0x0007 # UNSIGNED32
]:
o["bit_length"] = 2 ** (odi - 2)
o["data_type"] = "unsigned({:d} downto 0)".format(o.get("bit_length") - 1)
elif odi in [
0x000C, # TIME_OF_DAY
0x000D # TIME_DIFFERENCE
]:
o["bit_length"] = 48
o["data_type"] = "CanOpen.TimeOfDay"
elif odi == 0x000F: # DOMAIN
o["bit_length"] = 0 # variable, per CiA 301 section 7.4.7.1
o["data_type"] = "unsigned(31 downto 0)" # placeholder
else:
raise TypeError("Unsupported data type with index 0x{:04X}".format(odi))
return o
def format_signal(name, **kwargs):
name = format_constant(name, **{"prefix": "", "suffix": ""})
if "prefix" in kwargs:
prefix = kwargs["prefix"]
else:
prefix = "\\"
if "suffix" in kwargs:
suffix = kwargs["suffix"]
else:
suffix = "\\"
name = "".join(map(str.capitalize, name.split("_")))
return prefix + name + suffix
def format_value(value, bit_length):
s = ""
x = bit_length // 4
b = bit_length - (x * 4)
if b > 0:
s += ('b"{:0' + "{}".format(b) + 'b}"').format(value >> (x * 4)) # Will not truncate if value >= 2**bit_length
if x > 0:
s += " & "
if x > 0:
s += ('x"{:0' + "{}".format(x) + 'X}"').format(value & (2**(x * 4) - 1))
return s
def make_object(o):
obj = make_object_from_data_type(o.get("datatype"))
obj["parameter_name"] = o.get("parametername")
obj["access_type"] = o.get("accesstype")
name = obj.get("parameter_name")
default_value = o.get("defaultvalue")
bit_length = obj.get("bit_length")
if obj.get("access_type") =="const":
obj["name"] = format_constant(name)
default_value = int(default_value, 0)
obj["default_value"] = format_value(default_value, bit_length)
elif default_value is not None:
obj["name"] = format_signal(name)
if default_value.startswith("$NODEID"):
obj["default_value"] = "NodeId_q"
if len(default_value) > 7:
if default_value[7] != "+":
raise Exception(f"Invalid value syntax: {default_value}")
default_value = int(default_value[8:], 0)
if default_value < 0:
raise Exception(f"Negative $NODEID offsets are not allowed")
else:
default_value = 0
obj["default_value"] = f"{obj.get("data_type")[:obj.get("data_type").index("(")]}(resize(unsigned(NodeId_q), {bit_length}) + to_unsigned({default_value}, {bit_length}))"
else:
default_value = int(default_value, 0)
obj["default_value"] = format_value(default_value, bit_length)
else:
obj["name"] = format_signal(name)
obj["pdo_mapping"] = o.get("pdomapping", "0") == "1"
obj["direction"] = "in" if obj.get("access_type") == "ro" else "out"
if obj.get("access_type") in ["rw", "wo"]:
if o.get("lowlimit") is not None:
obj["low_limit"] = format_value(int(o.get("lowlimit"), 0), bit_length)
if o.get("highlimit") is not None:
obj["high_limit"] = format_value(int(o.get("highlimit"), 0), bit_length)
obj.update(make_object_from_data_type(o.get("datatype")))
print(o.get("parametername") + " => " + obj.get("name"))
return obj
def parse_cob_id(s):
if s.startswith("$NODEID+"):
s = s[8:]
return int(s, 0)
def zero_fill(l):
s = format_value(0, l)
if s != "":
s += " & "
return s
s = ""
x = l // 4
if x > 0:
s += 'x"' + "".ljust(x, "0") + '" & '
b = l - (x * 4)
if b > 0:
s += 'b"' + "".ljust(b, "0") + '" & '
return s
eds = ConfigParser(comment_prefixes=["#"])
eds.read(args.eds) # Loads in the EDS
#entity_name = "".join(map(str.capitalize, map(str.lower, eds["DeviceInfo"]["ProductName"].split(" ")))) + "CanOpen"
entity_name = format_signal(eds["DeviceInfo"]["ProductName"], prefix="", suffix="") + "CanOpen"
assert entity_name != ""
# Create pseudo-ObjectDictionary as a nested dict
indices = []
for section in ["MandatoryObjects", "OptionalObjects", "ManufacturerObjects"]:
if not eds.has_section(section): continue
n = int(eds[section]["SupportedObjects"], 0)
for i in range(1, n + 1):
indices.append(int(eds[section][str(i)], 0))
od = {}
for i in indices:
oc = eds["{:04X}".format(i)]
o = dict(oc)
sub_number = oc.get("SubNumber")
if sub_number is not None:
sub_number = int(sub_number, 0)
subs = {}
si = 0
while len(subs) <= sub_number and si <= 0xFF:
section = "{:04X}sub{:X}".format(i, si)
if eds.has_section(section):
subs.update({si: eds[section]})
si += 1
o['subs'] = subs
od.update({i: o})
if 0x100200 not in args.port:
args.port.append(0x100200)
port_signals = []
segmented_sdo = False;
# Create a flat, VHDL-friendly version of the object dictionary
objects = {}
for odi in od:
obj = od.get(odi)
if "subs" in obj:
subs = obj.get("subs")
for odsi in subs:
#if odsi == 0: continue
so = subs.get(odsi)
if odsi == 0:
so["parametername"] = obj.get("parametername") + " Length"
o = make_object(so)
objects.update({(odi << 8) + odsi: o})
if o.get("bit_length") == 0:
segmented_sdo = True
continue
if odi >= 0x2000 or ((odi << 8) + odsi) in args.port:
if o.get("access_type") in ["ro", "rw", "wo"]:
port_signals.append(o)
if o.get("access_type") == "wo":
port_signals.append({
"name": format_signal(so.get("parametername"), suffix="_strb\\"),
"direction": "out",
"data_type": "std_logic"
})
else:
try:
o = make_object(obj)
except Exception as e:
raise Exception("Error processing object 0x{:04X}".format(odi)) from e
objects.update({odi << 8: o})
if o.get("bit_length") == 0:
segmented_sdo = True
continue
if odi >= 0x2000 or (odi << 8) in args.port:
if o.get("access_type") in ["ro", "rw", "wo"]:
port_signals.append(o)
if o.get("access_type") == "wo":
port_signals.append({
"name": format_signal(o.get("parameter_name"), suffix="_strb\\"),
"direction": "out",
"data_type": "std_logic"
})
if 0x120001 not in objects:
segmented_sdo = False;
# Prepend optional port signals
if segmented_sdo:
port_signals.insert(0, {
"name": "SegmentedSdoDataValid",
"direction": "in",
"data_type": "std_logic"
})
port_signals.insert(0, {
"name": "SegmentedSdoData",
"direction": "in",
"data_type": "std_logic_vector(55 downto 0)"
})
port_signals.insert(0, {
"name": "SegmentedSdoReadDataEnable",
"direction": "out",
"data_type": "std_logic"
})
port_signals.insert(0, {
"name": "SegmentedSdoReadEnable",
"direction": "out",
"data_type": "std_logic"
})
port_signals.insert(0, {
"name": "SegmentedSdoMux",
"direction": "out",
"data_type": "std_logic_vector(23 downto 0)",
})
if args.timestamp:
port_signals.insert(0, {
"name": "Timestamp",
"direction": "out",
"data_type": "CanOpen.TimeOfDay"
})
if args.gfc:
port_signals.insert(0, {
"name": "Gfc",
"direction": "out",
"data_type": "std_logic"
})
if args.sync:
port_signals.insert(0, {
"name": "Sync",
"direction": "out",
"data_type": "std_logic"
})
for i in range(4, 0, -1):
cob_id_mux = ((0x1800 + i - 1) << 8) + 0x01
xtype_mux = ((0x1800 + i - 1) << 8) + 0x02
if xtype_mux in objects:
xtype = objects.get(xtype_mux)
if xtype.get("access_type") not in ["rw", "const"]:
raise ValueError(f"Access type for TPDO{i + 1} transmission type must be 'rw' or 'const'")
if xtype.get("access_type") in ["rw", "wo"] or (xtype.get("access_type") == "const" and int(od.get(xtype_mux >> 8).get("subs").get(xtype_mux & 0xFF).get("defaultvalue"), 0) in [0x00, 0xFD, 0xFE, 0xFF]):
port_signals.insert(0, {
"name": f"Tpdo{i}Event",
"direction": "in",
"data_type": "std_logic"
})
# Error checks
if 0x100000 not in objects:
raise ValueError("Device type is required")
if 0x100100 not in objects:
raise ValueError("Error register is required")
if 0x101800 not in objects:
raise ValueError("Identity object is required")
if 0x101801 not in objects:
raise ValueError("Vendor-ID is required")
names = []
for mux in objects:
name = objects.get(mux).get("name")
if name in names:
raise ValueError("Parameter names must be unique")
names.append(name)
template = """{0} {1} is
generic (
CLOCK_FREQUENCY : positive -- Frequency of Clock in Hz
);
port (
-- Common signals
Clock : in std_logic;
Reset_n : in std_logic;
CanRx : in std_logic;
CanTx : out std_logic;
NodeId : in std_logic_vector(6 downto 0);
ErrorRegister : in unsigned(7 downto 0);
Status : out CanOpen.Status;
-- Profile-specific signals
"""
template += ";\n".join(map(lambda signal: " " + signal.get("name").ljust(19) + " : " + signal.get("direction") + " " + signal.get("data_type"), port_signals))
template += """
);
end {0} {1};"""
fp = open(entity_name + ".vhd", "w")
fp.write("-- Generated with " + " ".join(argv) + "\n")
fp.write("""library ieee;
use ieee.std_logic_1164.all;
use ieee.std_logic_misc.all;
use ieee.numeric_std.all;
use work.CanBus;
use work.CanOpen;
""" + template.format("entity", entity_name, "" if len(port_signals) == 0 else ";") + """
architecture Behavioral of """ + entity_name + """ is
type State is (
STATE_RESET,
STATE_RESET_APP,
STATE_RESET_COMM,
STATE_BOOTUP,
STATE_BOOTUP_WAIT,
STATE_IDLE,
STATE_CAN_RX_STROBE,
STATE_CAN_RX_READ,
STATE_CAN_TX_STROBE,
STATE_CAN_TX_WAIT,
STATE_SYNC,
STATE_EMCY,
STATE_TPDO1,
STATE_TPDO2,
STATE_TPDO3,
STATE_TPDO4,
STATE_SDO_RX,
STATE_SDO_TX,
STATE_HEARTBEAT
);
component CanLite is
generic (
BAUD_RATE_PRESCALAR : positive range 1 to 64 := 1;
SYNCHRONIZATION_JUMP_WIDTH : positive range 1 to 4 := 3;
TIME_SEGMENT_1 : positive range 1 to 16 := 8;
TIME_SEGMENT_2 : positive range 1 to 8 := 3;
TRIPLE_SAMPLING : boolean := true
);
port (
Clock : in std_logic; -- Base clock for CAN timing (24MHz recommended)
Reset_n : in std_logic; -- Active-low reset
CanRx : in std_logic; -- RX input from CAN transceiver
CanTx : out std_logic; -- TX output to CAN transceiver
RxFrame : out CanBus.Frame; -- To RX FIFO
RxFifoWriteEnable : out std_logic; -- To RX FIFO
RxFifoFull : in std_logic; -- From RX FIFO
TxFrame : in CanBus.Frame; -- From TX FIFO
TxFifoReadEnable : out std_logic; -- To TX FIFO
TxFifoEmpty : in std_logic; -- From TX FIFO
TxAck : out std_logic; -- High pulse when a message was successfully transmitted
Status : out CanBus.Status -- See Can_pkg.vhdl
);
end component CanLite;
-- Internal signals
signal CurrentState,
NextState : State; -- Primary state machine variables
signal NodeId_q : std_logic_vector(6 downto 0); -- Latched node-ID
signal NmtState : std_logic_vector(6 downto 0);
signal RxFrame,
RxFrame_q,
TxFrame,
TxFrame_q : CanBus.Frame; -- CanLite frame interfacing
signal RxFifoReadEnable,
RxFifoWriteEnable,
RxFifoEmpty,
RxFifoFull,
TxFifoReadEnable,
TxFifoEmpty : std_logic; -- CanLite FIFO interface
signal SyncAck,
TxAck : std_logic; -- CanLite successful transmission
signal CanStatus : CanBus.Status; -- CanLite status
signal MicrosecondEnable,
HundredMicrosecondEnable,
MillisecondEnable : std_logic; -- Single-clock pulses
signal Sync_ob : std_logic; -- Sync pulse output buffer
signal InvalidConfiguration, -- Invalid NodeId
CommunicationError, -- Bit 4 of Error register
HeartbeatConsumerError, -- Heartbeat timeout event has occurred
SyncError, -- SYNC not received within communication cycle period
RpdoTimeout : std_logic;
signal EmcyEec : std_logic_vector(15 downto 0); -- Emergency error code
signal EmcyMsef : std_logic_vector(39 downto 0); -- Manufacturer-specific error code
signal Timestamp_ob : CanOpen.TimeOfDay;
""")
if 0x100500 in objects and 0x100600 in objects and 0x101900 in objects:
fp.write(""" signal SynchronousCounter : unsigned(7 downto 0);
""")
fp.write("""
-- Internal SDO signals
signal RxSdo,
TxSdo : std_logic_vector(63 downto 0);
signal RxSdoInitiateMux : std_logic_vector(23 downto 0);
signal Tpdo1Data,
Tpdo2Data,
Tpdo3Data,
Tpdo4Data : std_logic_vector(63 downto 0);
""")
if not segmented_sdo:
fp.write(""" signal SegmentedSdoMux : std_logic_vector(23 downto 0);
signal SegmentedSdoReadEnable : std_logic;
signal SegmentedSdoReadDataEnable : std_logic;
signal SegmentedSdoData : std_logic_vector(55 downto 0);
signal SegmentedSdoDataValid : std_logic;
""")
fp.write("""
-- Aliases for readability
alias RxCobIdFunctionCode : std_logic_vector(3 downto 0) is RxFrame_q.Id(10 downto 7);
alias RxCobIdNodeId : std_logic_vector(6 downto 0) is RxFrame_q.Id(6 downto 0);
alias RxNmtNodeControlCommand : std_logic_vector(7 downto 0) is RxFrame_q.Data(0);
alias RxNmtNodeControlNodeId : std_logic_vector(6 downto 0) is RxFrame_q.Data(1)(6 downto 0);
alias RxSdoCs : std_logic_vector(2 downto 0) is RxSdo(7 downto 5);
alias RxSdoInitiateMuxIndex : std_logic_vector(15 downto 0) is RxSdo(23 downto 8);
alias RxSdoInitiateMuxSubIndex : std_logic_vector(7 downto 0) is RxSdo(31 downto 24);
alias RxSdoDownloadInitiateN : std_logic_vector(1 downto 0) is RxSdo(3 downto 2);
alias RxSdoDownloadInitiateE : std_logic is RxSdo(1);
alias RxSdoDownloadInitiateS : std_logic is RxSdo(0);
alias RxSdoDownloadInitiateData : std_logic_vector(31 downto 0) is RxSdo(63 downto 32);
alias RxSdoUploadSegmentT : std_logic is RxSdo(4);
alias RxSdoUploadSegmentData : std_logic_vector(55 downto 0) is RxSdo(55 downto 0);
alias RxSdoBlockUploadCs : std_logic_vector is RxSdo(1 downto 0);
alias RxSdoBlockUploadInitiateCc : std_logic is RxSdo(2);
alias RxSdoBlockUploadInitiateBlksize : std_logic_vector(7 downto 0) is RxSdo(39 downto 32);
alias RxSdoBlockUploadInitiatePst : std_logic_vector(7 downto 0) is RxSdo(47 downto 40);
alias RxSdoBlockUploadSubBlockAckseq : std_logic_vector(7 downto 0) is RxSdo(15 downto 8);
alias RxSdoBlockUploadSubBlockBlksize : std_logic_vector(7 downto 0) is RxSdo(23 downto 16);
alias RxSdoBlockUploadEndN : std_logic_vector(2 downto 0) is RxSdo(4 downto 2);
alias RxSdoBlockUploadEndCrc : std_logic_vector(15 downto 0) is RxSdo(23 downto 8);
alias TxSdoCs : std_logic_vector(2 downto 0) is TxSdo(7 downto 5);
alias TxSdoInitiateMuxIndex : std_logic_vector(15 downto 0) is TxSdo(23 downto 8);
alias TxSdoInitiateMuxSubIndex : std_logic_vector(7 downto 0) is TxSdo(31 downto 24);
alias TxSdoAbortCode : std_logic_vector(31 downto 0) is TxSdo(63 downto 32);
alias TxSdoUploadInitiateN : std_logic_vector(1 downto 0) is TxSdo(3 downto 2);
alias TxSdoUploadInitiateE : std_logic is TxSdo(1);
alias TxSdoUploadInitiateS : std_logic is TxSdo(0);
alias TxSdoUploadInitiateD : std_logic_vector(31 downto 0) is TxSdo(63 downto 32);
alias TxSdoUploadSegmentT : std_logic is TxSdo(4);
alias TxSdoUploadSegmentN : std_logic_vector(2 downto 0) is TxSdo(3 downto 1);
alias TxSdoUploadSegmentC : std_logic is TxSdo(0);
alias TxSdoUploadSegmentSegData : std_logic_vector(55 downto 0) is TxSdo(63 downto 8);
alias TxSdoBlockUploadSs : std_logic is TxSdo(0);
alias TxSdoBlockUploadInitiateSc : std_logic is TxSdo(2);
alias TxSdoBlockUploadInitiateS : std_logic is TxSdo(1);
alias TxSdoBlockUploadInitiateSize : std_logic_vector(31 downto 0) is TxSdo(63 downto 32);
alias TxSdoBlockUploadSubBlockC : std_logic is TxSdo(7);
alias TxSdoBlockUploadSubBlockSeqno : std_logic_vector(6 downto 0) is TxSdo(6 downto 0);
alias TxSdoBlockUploadSubBlockSegData : std_logic_vector(55 downto 0) is TxSdo(63 downto 8);
alias TxSdoBlockUploadEndN : std_logic_vector(2 downto 0) is TxSdo(4 downto 2);
alias TxSdoBlockUploadEndCrc : std_logic_vector(15 downto 0) is TxSdo(23 downto 8);
-- Event triggers (unused)
""")
for i in range(1, 5):
cob_id_mux = ((0x1800 + i - 1) << 8) + 0x01
xtype_mux = ((0x1800 + i - 1) << 8) + 0x02
if xtype_mux in objects:
xtype = objects.get(xtype_mux)
if xtype.get("access_type") in ["const", "ro"] and int(od.get(xtype_mux >> 8).get("subs").get(xtype_mux & 0xFF).get("defaultvalue"), 0) in list(range(1, 0xFC)):
fp.write(f""" signal Tpdo{i}Event : std_logic;
""")
else:
fp.write(f""" signal Tpdo{i}Event : std_logic;
""")
fp.write("""
-- Interrupts
signal EmcyInterrupt,
HeartbeatProducerInterrupt,
SdoInterrupt,
SyncProducerInterrupt,
Tpdo1EventInterrupt,
Tpdo2EventInterrupt,
Tpdo3EventInterrupt,
Tpdo4EventInterrupt,
Tpdo1Interrupt,
Tpdo2Interrupt,
Tpdo3Interrupt,
Tpdo4Interrupt,
TpdoInterruptEnable,
Tpdo1InterruptEnable,
Tpdo2InterruptEnable,
Tpdo3InterruptEnable,
Tpdo4InterruptEnable,
Tpdo1RtrInterrupt,
Tpdo2RtrInterrupt,
Tpdo3RtrInterrupt,
Tpdo4RtrInterrupt : std_logic;
-- TPDO Counters / Timers
signal Tpdo1SyncCounter,
Tpdo2SyncCounter,
Tpdo3SyncCounter,
Tpdo4SyncCounter : unsigned(7 downto 0);
-- Object dictionary indices
""");
for odi in od:
obj = od.get(odi)
if "subnumber" in obj:
subs = obj.get("subs")
for odsi in subs:
if odsi == 0:
fp.write(" constant " + format_constant(obj.get("parametername"), prefix="\\ODI_", suffix="_LENGTH\\").ljust(26) + ' : std_logic_vector(23 downto 0) := x"{:04X}{:02X}";\n'.format(odi, odsi))
else:
fp.write(" constant " + format_constant(subs.get(odsi).get("parametername"), prefix="\\ODI_").ljust(26) + ' : std_logic_vector(23 downto 0) := x"{:04X}{:02X}";\n'.format(odi, odsi))
else:
fp.write(" constant " + format_constant(obj.get("parametername"), prefix="\\ODI_").ljust(26) + ' : std_logic_vector(23 downto 0) := x"{:04X}00";\n'.format(odi))
fp.write("""
-- Object dictionary entries
""")
for mux in objects:
obj = objects.get(mux)
if obj.get("access_type") == "const":
fp.write(" constant " + obj.get("name").ljust(26) + " : " + obj.get("data_type") + " := " + obj.get("default_value") + ";\n")
elif mux < 0x200000 and obj not in port_signals:
fp.write(" signal " + obj.get("name").ljust(28) + " : " + obj.get("data_type") + ";\n")
elif mux >= 0x200000 and obj.get("access_type") == "rw": # No additional declarations needed for mux >= 0x200000 and obj.get("access_type") in ["ro", "wo"]
fp.write(" signal " + format_signal(obj.get("parameter_name"), suffix="_q\\").ljust(28) + " : " + obj.get("data_type") + ";\n")
fp.write("""
begin
CanController : CanLite
port map (
Clock => Clock,
Reset_n => Reset_n,
CanRx => CanRx,
CanTx => CanTx,
RxFrame => RxFrame,
RxFifoWriteEnable => RxFifoWriteEnable,
RxFifoFull => RxFifoFull,
TxFrame => TxFrame_q,
TxFifoReadEnable => TxFifoReadEnable,
TxFifoEmpty => TxFifoEmpty,
TxAck => TxAck,
Status => CanStatus
);
-- Output signals
InvalidConfiguration <= '1' when NodeId = CanOpen.BROADCAST_NODE_ID else '0';
Status <= (
NmtState => NmtState,
CanStatus => CanStatus,
AutoBitrateOrLss => '0', -- TODO per CiA 801 and CiA 305
InvalidConfiguration => InvalidConfiguration,
ErrorControlEvent => HeartbeatConsumerError,
SyncError => SyncError,
EventTimerError => RpdoTimeout,
ProgramDownload => '0' -- TODO
);
""")
if args.sync:
fp.write(""" Sync <= Sync_ob; -- Buffered
""")
if args.gfc:
fp.write(""" Gfc <= '1' when CurrentState = STATE_CAN_RX_READ and RxCobIdFunctionCode = CanOpen.FUNCTION_CODE_NMT and RxCobIdNodeId = CanOpen.NMT_GFC else '0';
""")
fp.write("""
-- Single depth FIFO emulator for CanLite interface
RxFifoReadEnable <= '1' when CurrentState = STATE_CAN_RX_STROBE else '0';
RxFifoFull <= '0';
process (Reset_n, Clock)
begin
if Reset_n = '0' then
RxFrame_q <= (
Id => (others => '0'),
Rtr => '0',
Ide => '0',
Dlc => (others => '0'),
Data => (others => (others => '0'))
);
RxFifoEmpty <= '1';
TxFrame_q <= (
Id => (others => '0'),
Rtr => '0',
Ide => '0',
Dlc => (others => '0'),
Data => (others => (others => '0'))
);
TxFifoEmpty <= '1';
elsif rising_edge(Clock) then
if RxFifoWriteEnable = '1' then
RxFrame_q <= RxFrame;
end if;
if CanBus."="(CanStatus.State, CanBus.STATE_RESET) or CanBus."="(CanStatus.State, CanBus.STATE_BUS_OFF) then
RxFifoEmpty <= '1';
elsif RxFifoWriteEnable = '1' then
RxFifoEmpty <= '0';
elsif RxFifoReadEnable = '1' then
RxFifoEmpty <= '1';
end if;
if TxFifoReadEnable = '1' then
TxFrame_q <= TxFrame;
end if;
if CanBus."="(CanStatus.State, CanBus.STATE_RESET) or CanBus."="(CanStatus.State, CanBus.STATE_BUS_OFF) then
TxFifoEmpty <= '1';
elsif TxFifoReadEnable = '1' then
TxFifoEmpty <= '1';
elsif CurrentState = STATE_CAN_TX_STROBE then
TxFifoEmpty <= '0';
end if;
end if;
end process;
-- Primary state machine
process (Reset_n, Clock)
begin
if Reset_n = '0' then
CurrentState <= STATE_RESET;
elsif rising_edge(Clock) then
CurrentState <= NextState;
end if;
end process;
-- Next state in state machine
process (
""")
if 0x120001 in objects:
fp.write(" " + objects.get(0x120001).get("name") + ",\n")
fp.write(""" CurrentState,
TxAck,
CanStatus.State,
NodeId,
EmcyInterrupt,
HeartbeatProducerInterrupt,
SdoInterrupt,
SyncProducerInterrupt,
Tpdo1Interrupt,
Tpdo2Interrupt,
Tpdo3Interrupt,
Tpdo4Interrupt,
TxFifoEmpty,
RxFifoEmpty,
NmtState,
TxFifoReadEnable,
RxCobIdFunctionCode,
RxCobIdNodeId,
RxFrame_q.Dlc,
RxNmtNodeControlNodeId,
NodeId_q,
""")
if 0x120001 in objects:
obj = objects.get(0x120001)
fp.write(" " + obj.get("name") + """,
""")
fp.write(""" RxNmtNodeControlCommand
)
begin
case CurrentState is
when STATE_RESET => -- Power-on reset
NextState <= STATE_RESET_APP;
when STATE_RESET_APP => -- Service reset node
NextState <= STATE_RESET_COMM;
when STATE_RESET_COMM => -- Service reset communication
if CanBus."/="(CanStatus.State, CanBus.STATE_RESET) and CanBus."/="(CanStatus.State, CanBus.STATE_BUS_OFF) and NodeId /= CanOpen.BROADCAST_NODE_ID then -- Only boot if CAN bus is up and node-ID is valid
NextState <= STATE_BOOTUP;
else
NextState <= STATE_RESET_COMM;
end if;
when STATE_BOOTUP => -- Service boot-up Event
NextState <= STATE_CAN_TX_STROBE;
when STATE_BOOTUP_WAIT =>
if TxAck = '1' then -- Wait until boot-up message has been sent
NextState <= STATE_IDLE;
else
NextState <= STATE_BOOTUP_WAIT;
end if;
when STATE_IDLE => -- Wait for interrupt or reception of message from CanLite
if CanBus."="(CanStatus.State, CanBus.STATE_RESET) or CanBus."="(CanStatus.State, CanBus.STATE_BUS_OFF) then
NextState <= STATE_IDLE;
elsif RxFifoEmpty = '0' then
NextState <= STATE_CAN_RX_STROBE;
elsif TxFifoEmpty = '1' then
-- Transmit priority based on CiA 301 function codes
if SyncProducerInterrupt = '1' and (NmtState = CanOpen.NMT_STATE_PREOPERATIONAL or NmtState = CanOpen.NMT_STATE_OPERATIONAL) then
NextState <= STATE_SYNC;
elsif EmcyInterrupt = '1' and (NmtState = CanOpen.NMT_STATE_PREOPERATIONAL or NmtState = CanOpen.NMT_STATE_OPERATIONAL) then
NextState <= STATE_EMCY;
elsif Tpdo1Interrupt = '1' then
NextState <= STATE_TPDO1;
elsif Tpdo2Interrupt = '1' then
NextState <= STATE_TPDO2;
elsif Tpdo3Interrupt = '1' then
NextState <= STATE_TPDO3;
elsif Tpdo4Interrupt = '1' then
NextState <= STATE_TPDO4;
elsif SdoInterrupt = '1' then
NextState <= STATE_SDO_TX;
elsif HeartbeatProducerInterrupt = '1' then
NextState <= STATE_HEARTBEAT;
else
NextState <= STATE_IDLE;
end if;
else
NextState <= STATE_IDLE;
end if;
when STATE_SYNC =>
NextState <= STATE_CAN_TX_STROBE;
when STATE_EMCY =>
NextState <= STATE_CAN_TX_STROBE;
when STATE_TPDO1 =>
NextState <= STATE_CAN_TX_STROBE;
when STATE_TPDO2 =>
NextState <= STATE_CAN_TX_STROBE;
when STATE_TPDO3 =>
NextState <= STATE_CAN_TX_STROBE;
when STATE_TPDO4 =>
NextState <= STATE_CAN_TX_STROBE;
when STATE_SDO_TX =>
NextState <= STATE_CAN_TX_STROBE;
when STATE_HEARTBEAT =>
NextState <= STATE_CAN_TX_STROBE;
when STATE_CAN_TX_STROBE =>
NextState <= STATE_CAN_TX_WAIT;
when STATE_CAN_TX_WAIT => -- Wait until message has been loaded into CanLite
if NmtState = CanOpen.NMT_STATE_INITIALISATION then
NextState <= STATE_BOOTUP_WAIT;
elsif TxFifoReadEnable = '1' then
NextState <= STATE_IDLE;
else
NextState <= STATE_CAN_TX_WAIT;
end if;
when STATE_CAN_RX_STROBE => -- Load message from CanLite
NextState <= STATE_CAN_RX_READ;
when STATE_CAN_RX_READ => -- Process message
if RxCobIdFunctionCode = CanOpen.FUNCTION_CODE_NMT and RxCobIdNodeId = CanOpen.NMT_NODE_CONTROL and (RxNmtNodeControlNodeId = CanOpen.BROADCAST_NODE_ID or RxNmtNodeControlNodeId = NodeId_q) then
if RxNmtNodeControlCommand = CanOpen.NMT_NODE_CONTROL_RESET_APP then
NextState <= STATE_RESET_APP;
elsif RxNmtNodeControlCommand = CanOpen.NMT_NODE_CONTROL_RESET_COMM then
NextState <= STATE_RESET_COMM;
else
NextState <= STATE_IDLE;
end if;""")
if 0x120001 in objects:
obj = objects.get(0x120001)
fp.write("""
elsif {0}(31) = '0' and CanOpen.is_match(RxFrame_q, {0}) and RxFrame_q.Dlc(3) = '1' then -- SDO Request, ignore if not 8 data bytes
NextState <= STATE_SDO_RX;""".format(obj.get("name")))
fp.write("""
else
NextState <= STATE_IDLE;
end if;
when STATE_SDO_RX =>
NextState <= STATE_IDLE;
when others =>
NextState <= STATE_RESET;
end case;
end process;
-- NMT State determination
process (Clock, Reset_n)
begin
if Reset_n = '0' then
NmtState <= CanOpen.NMT_STATE_INITIALISATION;
elsif rising_edge(Clock) then
""")
if 0x102901 in objects:
fp.write(""" if CommunicationError = '1' and NmtState = CanOpen.NMT_STATE_OPERATIONAL and std_logic_vector({0}) = x"00" then
NmtState <= CanOpen.NMT_STATE_PREOPERATIONAL;
elsif CommunicationError = '1' and std_logic_vector({0}) = x"02" then
NmtState <= CanOpen.NMT_STATE_STOPPED;
""".format(objects.get(0x102901).get("name")))
if 0x102902 in objects:
fp.write(""" elsif {0}(0) = '1' and NmtState = CanOpen.NMT_STATE_OPERATIONAL and {1} = x"00" then
NmtState <= CanOpen.NMT_STATE_PREOPERATIONAL;
elsif {0}(0) = '1' and {1} = x"02" then
NmtState <= CanOpen.NMT_STATE_STOPPED;
""".format(objects.get(0x100100).get("name"), objects.get(0x102902).get("name")))
else:
fp.write(""" if CommunicationError = '1' and NmtState = CanOpen.NMT_STATE_OPERATIONAL then
NmtState <= CanOpen.NMT_STATE_PREOPERATIONAL; -- Default behavior if the Communication error entry (0x01) of the Error behavior object (0x1029) not supported, per CiA 301
""")
fp.write(""" else
case CurrentState is
when STATE_RESET =>
NmtState <= CanOpen.NMT_STATE_INITIALISATION;
when STATE_RESET_APP =>
NmtState <= CanOpen.NMT_STATE_INITIALISATION;
when STATE_RESET_COMM =>
NmtState <= CanOpen.NMT_STATE_INITIALISATION;
when STATE_BOOTUP =>
NmtState <= CanOpen.NMT_STATE_INITIALISATION;
when STATE_BOOTUP_WAIT =>
if TxAck = '1' then
""")
if 0x1F8000 in objects:
fp.write(""" if {0}(3) = '1' then
NmtState <= CanOpen.NMT_STATE_OPERATIONAL;
else
NmtState <= CanOpen.NMT_STATE_PREOPERATIONAL;
end if;
""".format(objects.get(0x1F8000).get("name")))
else:
fp.write(""" NmtState <= CanOpen.NMT_STATE_PREOPERATIONAL;
""")
fp.write(""" else
NmtState <= CanOpen.NMT_STATE_INITIALISATION;
end if;
when STATE_CAN_RX_READ =>
if RxCobIdFunctionCode = CanOpen.FUNCTION_CODE_NMT and RxCobIdNodeId = CanOpen.NMT_NODE_CONTROL and (RxNmtNodeControlNodeId = NodeId_q or RxNmtNodeControlNodeId = CanOpen.BROADCAST_NODE_ID) then
case RxNmtNodeControlCommand is
when CanOpen.NMT_NODE_CONTROL_OPERATIONAL =>
NmtState <= CanOpen.NMT_STATE_OPERATIONAL;
when CanOpen.NMT_NODE_CONTROL_PREOPERATIONAL =>
NmtState <= CanOpen.NMT_STATE_PREOPERATIONAL;
when CanOpen.NMT_NODE_CONTROL_STOPPED =>
NmtState <= CanOpen.NMT_STATE_STOPPED;
when others =>
end case;
end if;
when others =>
end case;
end if;
end if;
end process;
-- Latch node-ID
process (Reset_n, Clock)
begin
if Reset_n = '0' then
NodeId_q <= CanOpen.BROADCAST_NODE_ID;
elsif rising_edge(Clock) then
if CurrentState = STATE_RESET_COMM then
NodeId_q <= NodeId;
end if;
end if;
end process;
-- TIME handling""")
if args.timestamp:
fp.write("""
Timestamp <= Timestamp_ob;""")
fp.write("""
process (Reset_n, Clock)
begin
if Reset_n = '0' then
Timestamp_ob <= (
Milliseconds => (others => '0'),
Days => (others => '0')
);
elsif rising_edge(Clock) then
""")
if 0x101200 in objects:
fp.write("""if
CurrentState = STATE_CAN_RX_READ and
{0}(31) = '1' and
CanOpen.is_match(RxFrame_q, {0}) and
RxFrame_q.Dlc = b"0110"
then
Timestamp_ob <= CanOpen.to_TimeOfDay(RxFrame_q.Data);
els""".format(objects.get(0x101200).get("name")))
fp.write("""if MillisecondEnable = '1' then
if Timestamp_ob.Milliseconds = 1000 * 60 * 60 * 24 - 1 then
Timestamp_ob.Milliseconds <= (others => '0');
Timestamp_ob.Days <= Timestamp_ob.Days + 1;
else
Timestamp_ob.Milliseconds <= Timestamp_ob.Milliseconds + 1;
end if;
end if;
end if;
end process;
-- Sync producer timer""")
if 0x100500 in objects and 0x100600 in objects:
fp.write("""
process (Reset_n, Clock)
variable SyncPending : boolean;
variable SyncCounter : unsigned(31 downto 0);
begin
if Reset_n = '0' then
SyncPending := false;
SyncCounter := (others => '0');
SyncProducerInterrupt <= '0';
SyncAck <= '0';
SyncError <= '0';
elsif rising_edge(Clock) then
if (
NmtState = CanOpen.NMT_STATE_INITIALISATION
or NmtState = CanOpen.NMT_STATE_STOPPED
or {1} = 0
or CurrentState = STATE_RESET_COMM
or (CurrentState = STATE_SDO_TX and TxSdoCs = CanOpen.SDO_SCS_IDR and TxSdoInitiateMuxIndex = x"1006" and TxSdoInitiateMuxSubIndex = x"00") -- Successful SDO Download
) then
SyncCounter := (others => '0');
SyncError <= '0';
elsif {0}(0) = '0' and Sync_ob = '1' then
SyncCounter := (others => '0');
SyncError <= '0';
elsif MicrosecondEnable = '1' then
if SyncCounter < {1} - 1 then
SyncCounter := SyncCounter + 1;
else
SyncCounter := (others => '0');
if {0}(0) = '0' then
SyncError <= '1';
else
SyncError <= '0';
end if;
end if;
end if;
if {0}(30) = '0' then
SyncProducerInterrupt <= '0';
elsif MicrosecondEnable = '1' and SyncCounter = {1} - 1 then
SyncProducerInterrupt <= '1';
elsif CurrentState = STATE_SYNC then
SyncPending := true;
SyncProducerInterrupt <= '0';
end if;
if SyncPending and TxAck = '1' then
SyncAck <= '1';
else
SyncAck <= '0';
end if;
end if;
end process;
""".format(objects.get(0x100500).get("name"), objects.get(0x100600).get("name")))
if 0x101900 in objects:
fp.write("""
-- NOTE: CiA 301 requires an SDO abort to a change of 0x1019 if 0x1006 is not zero (TODO). Instead, a change will reset the counter to zero.
process (Reset_n, Clock)
begin
if Reset_n = '0' then
SynchronousCounter <= to_unsigned(1, SynchronousCounter'length);
elsif rising_edge(Clock) then
if (
NmtState = CanOpen.NMT_STATE_INITIALISATION
or NmtState = CanOpen.NMT_STATE_STOPPED
or CurrentState = STATE_RESET_COMM
or (CurrentState = STATE_SDO_TX and TxSdoCs = CanOpen.SDO_SCS_IDR and TxSdoInitiateMuxIndex = x"1019" and TxSdoInitiateMuxSubIndex = x"00") -- Successful SDO Download
or {0} < 2 or {0} > 240
) then
SynchronousCounter <= to_unsigned(1, SynchronousCounter'length);
elsif SyncAck = '1' then
if SynchronousCounter < {0} then
SynchronousCounter <= SynchronousCounter + 1;
else
SynchronousCounter <= to_unsigned(1, SynchronousCounter'length);
end if;
end if;
end if;
end process;
""".format(objects.get(0x101900).get("name")))