forked from hardbyte/python-can
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbit_timing.py
More file actions
1090 lines (924 loc) · 37.2 KB
/
bit_timing.py
File metadata and controls
1090 lines (924 loc) · 37.2 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
# pylint: disable=too-many-lines
import math
from typing import List, Mapping, Iterator, cast
from can.typechecking import BitTimingFdDict, BitTimingDict
class BitTiming(Mapping):
"""Representation of a bit timing configuration for a CAN 2.0 bus.
The class can be constructed in multiple ways, depending on the information
available. The preferred way is using CAN clock frequency, prescaler, tseg1, tseg2 and sjw::
can.BitTiming(f_clock=8_000_000, brp=1, tseg1=5, tseg2=1, sjw=1)
Alternatively you can set the bitrate instead of the bit rate prescaler::
can.BitTiming.from_bitrate_and_segments(
f_clock=8_000_000, bitrate=1_000_000, tseg1=5, tseg2=1, sjw=1
)
It is also possible to specify BTR registers::
can.BitTiming.from_registers(f_clock=8_000_000, btr0=0x00, btr1=0x14)
or to calculate the timings for a given sample point::
can.BitTiming.from_sample_point(f_clock=8_000_000, bitrate=1_000_000, sample_point=75.0)
"""
def __init__(
self,
f_clock: int,
brp: int,
tseg1: int,
tseg2: int,
sjw: int,
nof_samples: int = 1,
) -> None:
"""
:param int f_clock:
The CAN system clock frequency in Hz.
:param int brp:
Bit rate prescaler.
:param int tseg1:
Time segment 1, that is, the number of quanta from (but not including)
the Sync Segment to the sampling point.
:param int tseg2:
Time segment 2, that is, the number of quanta from the sampling
point to the end of the bit.
:param int sjw:
The Synchronization Jump Width. Decides the maximum number of time quanta
that the controller can resynchronize every bit.
:param int nof_samples:
Either 1 or 3. Some CAN controllers can also sample each bit three times.
In this case, the bit will be sampled three quanta in a row,
with the last sample being taken in the edge between TSEG1 and TSEG2.
Three samples should only be used for relatively slow baudrates.
:raises ValueError:
if the arguments are invalid.
"""
self._data: BitTimingDict = {
"f_clock": f_clock,
"brp": brp,
"tseg1": tseg1,
"tseg2": tseg2,
"sjw": sjw,
"nof_samples": nof_samples,
}
self._validate()
def _validate(self) -> None:
if not 8 <= self.nbt <= 25:
raise ValueError(f"nominal bit time (={self.nbt}) must be in [8...25].")
if not 1 <= self.brp <= 64:
raise ValueError(f"bitrate prescaler (={self.brp}) must be in [1...64].")
if not 5_000 <= self.bitrate <= 2_000_000:
raise ValueError(
f"bitrate (={self.bitrate}) must be in [5,000...2,000,000]."
)
if not 1 <= self.tseg1 <= 16:
raise ValueError(f"tseg1 (={self.tseg1}) must be in [1...16].")
if not 1 <= self.tseg2 <= 8:
raise ValueError(f"tseg2 (={self.tseg2}) must be in [1...8].")
if not 1 <= self.sjw <= 4:
raise ValueError(f"sjw (={self.sjw}) must be in [1...4].")
if self.sjw > self.tseg2:
raise ValueError(
f"sjw (={self.sjw}) must not be greater than tseg2 (={self.tseg2})."
)
if self.sample_point < 50.0:
raise ValueError(
f"The sample point must be greater than or equal to 50% "
f"(sample_point={self.sample_point:.2f}%)."
)
if self.nof_samples not in (1, 3):
raise ValueError("nof_samples must be 1 or 3")
@classmethod
def from_bitrate_and_segments(
cls,
f_clock: int,
bitrate: int,
tseg1: int,
tseg2: int,
sjw: int,
nof_samples: int = 1,
) -> "BitTiming":
"""Create a :class:`~can.BitTiming` instance from bitrate and segment lengths.
:param int f_clock:
The CAN system clock frequency in Hz.
:param int bitrate:
Bitrate in bit/s.
:param int tseg1:
Time segment 1, that is, the number of quanta from (but not including)
the Sync Segment to the sampling point.
:param int tseg2:
Time segment 2, that is, the number of quanta from the sampling
point to the end of the bit.
:param int sjw:
The Synchronization Jump Width. Decides the maximum number of time quanta
that the controller can resynchronize every bit.
:param int nof_samples:
Either 1 or 3. Some CAN controllers can also sample each bit three times.
In this case, the bit will be sampled three quanta in a row,
with the last sample being taken in the edge between TSEG1 and TSEG2.
Three samples should only be used for relatively slow baudrates.
:raises ValueError:
if the arguments are invalid.
"""
try:
brp = int(round(f_clock / (bitrate * (1 + tseg1 + tseg2))))
except ZeroDivisionError:
raise ValueError("Invalid inputs") from None
bt = cls(
f_clock=f_clock,
brp=brp,
tseg1=tseg1,
tseg2=tseg2,
sjw=sjw,
nof_samples=nof_samples,
)
if abs(bt.bitrate - bitrate) > bitrate / 256:
raise ValueError(
f"the effective bitrate (={bt.bitrate}) diverges "
f"from the requested bitrate (={bitrate})"
)
return bt
@classmethod
def from_registers(
cls,
f_clock: int,
btr0: int,
btr1: int,
) -> "BitTiming":
"""Create a :class:`~can.BitTiming` instance from registers btr0 and btr1.
:param int f_clock:
The CAN system clock frequency in Hz.
:param int btr0:
The BTR0 register value used by many CAN controllers.
:param int btr1:
The BTR1 register value used by many CAN controllers.
:raises ValueError:
if the arguments are invalid.
"""
brp = (btr0 & 0x3F) + 1
sjw = (btr0 >> 6) + 1
tseg1 = (btr1 & 0xF) + 1
tseg2 = ((btr1 >> 4) & 0x7) + 1
nof_samples = 3 if btr1 & 0x80 else 1
return cls(
brp=brp,
f_clock=f_clock,
tseg1=tseg1,
tseg2=tseg2,
sjw=sjw,
nof_samples=nof_samples,
)
@classmethod
def from_sample_point(
cls, f_clock: int, bitrate: int, sample_point: float = 69.0
) -> "BitTiming":
"""Create a :class:`~can.BitTiming` instance for a sample point.
This function tries to find bit timings, which are close to the requested
sample point. It does not take physical bus properties into account, so the
calculated bus timings might not work properly for you.
The :func:`oscillator_tolerance` function might be helpful to evaluate the
bus timings.
:param int f_clock:
The CAN system clock frequency in Hz.
:param int bitrate:
Bitrate in bit/s.
:param int sample_point:
The sample point value in percent.
:raises ValueError:
if the arguments are invalid.
"""
if sample_point < 50.0:
raise ValueError(f"sample_point (={sample_point}) must not be below 50%.")
possible_solutions: List[BitTiming] = []
for brp in range(1, 65):
nbt = round(int(f_clock / (bitrate * brp)))
if nbt < 8:
break
effective_bitrate = f_clock / (nbt * brp)
if abs(effective_bitrate - bitrate) > bitrate / 256:
continue
tseg1 = int(round(sample_point / 100 * nbt)) - 1
# limit tseg1, so tseg2 is at least 1 TQ
tseg1 = min(tseg1, nbt - 2)
tseg2 = nbt - tseg1 - 1
sjw = min(tseg2, 4)
try:
bt = BitTiming(
f_clock=f_clock,
brp=brp,
tseg1=tseg1,
tseg2=tseg2,
sjw=sjw,
)
possible_solutions.append(bt)
except ValueError:
continue
if not possible_solutions:
raise ValueError("No suitable bit timings found.")
# sort solutions
for key, reverse in (
# prefer low prescaler
(lambda x: x.brp, False),
# prefer low sample point deviation from requested values
(lambda x: abs(x.sample_point - sample_point), False),
):
possible_solutions.sort(key=key, reverse=reverse)
return possible_solutions[0]
@property
def f_clock(self) -> int:
"""The CAN system clock frequency in Hz."""
return self._data["f_clock"]
@property
def bitrate(self) -> int:
"""Bitrate in bits/s."""
return int(round(self.f_clock / (self.nbt * self.brp)))
@property
def brp(self) -> int:
"""Bit Rate Prescaler."""
return self._data["brp"]
@property
def tq(self) -> int:
"""Time quantum in nanoseconds"""
return int(round(self.brp / self.f_clock * 1e9))
@property
def nbt(self) -> int:
"""Nominal Bit Time."""
return 1 + self.tseg1 + self.tseg2
@property
def tseg1(self) -> int:
"""Time segment 1.
The number of quanta from (but not including) the Sync Segment to the sampling point.
"""
return self._data["tseg1"]
@property
def tseg2(self) -> int:
"""Time segment 2.
The number of quanta from the sampling point to the end of the bit.
"""
return self._data["tseg2"]
@property
def sjw(self) -> int:
"""Synchronization Jump Width."""
return self._data["sjw"]
@property
def nof_samples(self) -> int:
"""Number of samples (1 or 3)."""
return self._data["nof_samples"]
@property
def sample_point(self) -> float:
"""Sample point in percent."""
return 100.0 * (1 + self.tseg1) / (1 + self.tseg1 + self.tseg2)
@property
def btr0(self) -> int:
"""Bit timing register 0."""
return (self.sjw - 1) << 6 | self.brp - 1
@property
def btr1(self) -> int:
"""Bit timing register 1."""
sam = 1 if self.nof_samples == 3 else 0
return sam << 7 | (self.tseg2 - 1) << 4 | self.tseg1 - 1
def oscillator_tolerance(
self,
node_loop_delay_ns: float = 250.0,
bus_length_m: float = 10.0,
) -> float:
"""Oscillator tolerance in percent according to ISO 11898-1.
:param float node_loop_delay_ns:
Transceiver loop delay in nanoseconds.
:param float bus_length_m:
Bus length in meters.
"""
delay_per_meter = 5
bidirectional_propagation_delay_ns = 2 * (
node_loop_delay_ns + delay_per_meter * bus_length_m
)
prop_seg = math.ceil(bidirectional_propagation_delay_ns / self.tq)
nom_phase_seg1 = self.tseg1 - prop_seg
nom_phase_seg2 = self.tseg2
df_clock_list = [
_oscillator_tolerance_condition_1(nom_sjw=self.sjw, nbt=self.nbt),
_oscillator_tolerance_condition_2(
nbt=self.nbt,
nom_phase_seg1=nom_phase_seg1,
nom_phase_seg2=nom_phase_seg2,
),
]
return max(0.0, min(df_clock_list) * 100)
def recreate_with_f_clock(self, f_clock: int) -> "BitTiming":
"""Return a new :class:`~can.BitTiming` instance with the given *f_clock* but the same
bit rate and sample point.
:param int f_clock:
The CAN system clock frequency in Hz.
:raises ValueError:
if no suitable bit timings were found.
"""
# try the most simple solution first: another bitrate prescaler
try:
return BitTiming.from_bitrate_and_segments(
f_clock=f_clock,
bitrate=self.bitrate,
tseg1=self.tseg1,
tseg2=self.tseg2,
sjw=self.sjw,
nof_samples=self.nof_samples,
)
except ValueError:
pass
# create a new timing instance with the same sample point
bt = BitTiming.from_sample_point(
f_clock=f_clock, bitrate=self.bitrate, sample_point=self.sample_point
)
if abs(bt.sample_point - self.sample_point) > 1.0:
raise ValueError(
"f_clock change failed because of sample point discrepancy."
)
# adapt synchronization jump width, so it has the same size relative to bit time as self
sjw = int(round(self.sjw / self.nbt * bt.nbt))
sjw = max(1, min(4, bt.tseg2, sjw))
bt._data["sjw"] = sjw # pylint: disable=protected-access
bt._data["nof_samples"] = self.nof_samples # pylint: disable=protected-access
bt._validate() # pylint: disable=protected-access
return bt
def __str__(self) -> str:
segments = [
f"BR: {self.bitrate:_} bit/s",
f"SP: {self.sample_point:.2f}%",
f"BRP: {self.brp}",
f"TSEG1: {self.tseg1}",
f"TSEG2: {self.tseg2}",
f"SJW: {self.sjw}",
f"BTR: {self.btr0:02X}{self.btr1:02X}h",
f"CLK: {self.f_clock / 1e6:.0f}MHz",
]
return ", ".join(segments)
def __repr__(self) -> str:
args = ", ".join(f"{key}={value}" for key, value in self.items())
return f"can.{self.__class__.__name__}({args})"
def __getitem__(self, key: str) -> int:
return cast(int, self._data.__getitem__(key))
def __len__(self) -> int:
return self._data.__len__()
def __iter__(self) -> Iterator[str]:
return self._data.__iter__()
def __eq__(self, other: object) -> bool:
if not isinstance(other, BitTiming):
return False
return self._data == other._data
def __hash__(self) -> int:
return tuple(self._data.values()).__hash__()
class BitTimingFd(Mapping):
"""Representation of a bit timing configuration for a CAN FD bus.
The class can be constructed in multiple ways, depending on the information
available. The preferred way is using CAN clock frequency, bit rate prescaler, tseg1,
tseg2 and sjw for both the arbitration (nominal) and data phase::
can.BitTimingFd(
f_clock=80_000_000,
nom_brp=1,
nom_tseg1=59,
nom_tseg2=20,
nom_sjw=10,
data_brp=1,
data_tseg1=6,
data_tseg2=3,
data_sjw=2,
)
Alternatively you can set the bit rates instead of the bit rate prescalers::
can.BitTimingFd.from_bitrate_and_segments(
f_clock=80_000_000,
nom_bitrate=1_000_000,
nom_tseg1=59,
nom_tseg2=20,
nom_sjw=10,
data_bitrate=8_000_000,
data_tseg1=6,
data_tseg2=3,
data_sjw=2,
)
It is also possible to calculate the timings for a given
pair of arbitration and data sample points::
can.BitTimingFd.from_sample_point(
f_clock=80_000_000,
nom_bitrate=1_000_000,
nom_sample_point=75.0,
data_bitrate=8_000_000,
data_sample_point=70.0,
)
"""
def __init__(
self,
f_clock: int,
nom_brp: int,
nom_tseg1: int,
nom_tseg2: int,
nom_sjw: int,
data_brp: int,
data_tseg1: int,
data_tseg2: int,
data_sjw: int,
) -> None:
"""
Initialize a BitTimingFd instance with the specified parameters.
:param int f_clock:
The CAN system clock frequency in Hz.
:param int nom_brp:
Nominal (arbitration) phase bitrate prescaler.
:param int nom_tseg1:
Nominal phase Time segment 1, that is, the number of quanta from (but not including)
the Sync Segment to the sampling point.
:param int nom_tseg2:
Nominal phase Time segment 2, that is, the number of quanta from the sampling
point to the end of the bit.
:param int nom_sjw:
The Synchronization Jump Width for the nominal phase. This value determines
the maximum number of time quanta that the controller can resynchronize every bit.
:param int data_brp:
Data phase bitrate prescaler.
:param int data_tseg1:
Data phase Time segment 1, that is, the number of quanta from (but not including)
the Sync Segment to the sampling point.
:param int data_tseg2:
Data phase Time segment 2, that is, the number of quanta from the sampling
point to the end of the bit.
:param int data_sjw:
The Synchronization Jump Width for the data phase. This value determines
the maximum number of time quanta that the controller can resynchronize every bit.
:raises ValueError:
if the arguments are invalid.
"""
self._data: BitTimingFdDict = {
"f_clock": f_clock,
"nom_brp": nom_brp,
"nom_tseg1": nom_tseg1,
"nom_tseg2": nom_tseg2,
"nom_sjw": nom_sjw,
"data_brp": data_brp,
"data_tseg1": data_tseg1,
"data_tseg2": data_tseg2,
"data_sjw": data_sjw,
}
self._validate()
def _validate(self) -> None:
if self.nbt < 8:
raise ValueError(f"nominal bit time (={self.nbt}) must be at least 8.")
if self.dbt < 8:
raise ValueError(f"data bit time (={self.dbt}) must be at least 8.")
if not 1 <= self.nom_brp <= 256:
raise ValueError(
f"nominal bitrate prescaler (={self.nom_brp}) must be in [1...256]."
)
if not 1 <= self.data_brp <= 256:
raise ValueError(
f"data bitrate prescaler (={self.data_brp}) must be in [1...256]."
)
if not 5_000 <= self.nom_bitrate <= 2_000_000:
raise ValueError(
f"nom_bitrate (={self.nom_bitrate}) must be in [5,000...2,000,000]."
)
if not 25_000 <= self.data_bitrate <= 8_000_000:
raise ValueError(
f"data_bitrate (={self.data_bitrate}) must be in [25,000...8,000,000]."
)
if self.data_bitrate < self.nom_bitrate:
raise ValueError(
f"data_bitrate (={self.data_bitrate}) must be greater than or "
f"equal to nom_bitrate (={self.nom_bitrate})"
)
if not 2 <= self.nom_tseg1 <= 256:
raise ValueError(f"nom_tseg1 (={self.nom_tseg1}) must be in [2...256].")
if not 1 <= self.nom_tseg2 <= 128:
raise ValueError(f"nom_tseg2 (={self.nom_tseg2}) must be in [1...128].")
if not 1 <= self.data_tseg1 <= 32:
raise ValueError(f"data_tseg1 (={self.data_tseg1}) must be in [1...32].")
if not 1 <= self.data_tseg2 <= 16:
raise ValueError(f"data_tseg2 (={self.data_tseg2}) must be in [1...16].")
if not 1 <= self.nom_sjw <= 128:
raise ValueError(f"nom_sjw (={self.nom_sjw}) must be in [1...128].")
if self.nom_sjw > self.nom_tseg2:
raise ValueError(
f"nom_sjw (={self.nom_sjw}) must not be "
f"greater than nom_tseg2 (={self.nom_tseg2})."
)
if not 1 <= self.data_sjw <= 16:
raise ValueError(f"data_sjw (={self.data_sjw}) must be in [1...128].")
if self.data_sjw > self.data_tseg2:
raise ValueError(
f"data_sjw (={self.data_sjw}) must not be "
f"greater than data_tseg2 (={self.data_tseg2})."
)
if self.nom_sample_point < 50.0:
raise ValueError(
f"The arbitration sample point must be greater than or equal to 50% "
f"(nom_sample_point={self.nom_sample_point:.2f}%)."
)
if self.data_sample_point < 50.0:
raise ValueError(
f"The data sample point must be greater than or equal to 50% "
f"(data_sample_point={self.data_sample_point:.2f}%)."
)
@classmethod
def from_bitrate_and_segments(
cls,
f_clock: int,
nom_bitrate: int,
nom_tseg1: int,
nom_tseg2: int,
nom_sjw: int,
data_bitrate: int,
data_tseg1: int,
data_tseg2: int,
data_sjw: int,
) -> "BitTimingFd":
"""
Create a :class:`~can.BitTimingFd` instance with the bitrates and segments lengths.
:param int f_clock:
The CAN system clock frequency in Hz.
:param int nom_bitrate:
Nominal (arbitration) phase bitrate in bit/s.
:param int nom_tseg1:
Nominal phase Time segment 1, that is, the number of quanta from (but not including)
the Sync Segment to the sampling point.
:param int nom_tseg2:
Nominal phase Time segment 2, that is, the number of quanta from the sampling
point to the end of the bit.
:param int nom_sjw:
The Synchronization Jump Width for the nominal phase. This value determines
the maximum number of time quanta that the controller can resynchronize every bit.
:param int data_bitrate:
Data phase bitrate in bit/s.
:param int data_tseg1:
Data phase Time segment 1, that is, the number of quanta from (but not including)
the Sync Segment to the sampling point.
:param int data_tseg2:
Data phase Time segment 2, that is, the number of quanta from the sampling
point to the end of the bit.
:param int data_sjw:
The Synchronization Jump Width for the data phase. This value determines
the maximum number of time quanta that the controller can resynchronize every bit.
:raises ValueError:
if the arguments are invalid.
"""
try:
nom_brp = int(round(f_clock / (nom_bitrate * (1 + nom_tseg1 + nom_tseg2))))
data_brp = int(
round(f_clock / (data_bitrate * (1 + data_tseg1 + data_tseg2)))
)
except ZeroDivisionError:
raise ValueError("Invalid inputs.") from None
bt = cls(
f_clock=f_clock,
nom_brp=nom_brp,
nom_tseg1=nom_tseg1,
nom_tseg2=nom_tseg2,
nom_sjw=nom_sjw,
data_brp=data_brp,
data_tseg1=data_tseg1,
data_tseg2=data_tseg2,
data_sjw=data_sjw,
)
if abs(bt.nom_bitrate - nom_bitrate) > nom_bitrate / 256:
raise ValueError(
f"the effective nom. bitrate (={bt.nom_bitrate}) diverges "
f"from the requested nom. bitrate (={nom_bitrate})"
)
if abs(bt.data_bitrate - data_bitrate) > data_bitrate / 256:
raise ValueError(
f"the effective data bitrate (={bt.data_bitrate}) diverges "
f"from the requested data bitrate (={data_bitrate})"
)
return bt
@classmethod
def from_sample_point(
cls,
f_clock: int,
nom_bitrate: int,
nom_sample_point: float,
data_bitrate: int,
data_sample_point: float,
) -> "BitTimingFd":
"""Create a :class:`~can.BitTimingFd` instance for a given nominal/data sample point pair.
This function tries to find bit timings, which are close to the requested
sample points. It does not take physical bus properties into account, so the
calculated bus timings might not work properly for you.
The :func:`oscillator_tolerance` function might be helpful to evaluate the
bus timings.
:param int f_clock:
The CAN system clock frequency in Hz.
:param int nom_bitrate:
Nominal bitrate in bit/s.
:param int nom_sample_point:
The sample point value of the arbitration phase in percent.
:param int data_bitrate:
Data bitrate in bit/s.
:param int data_sample_point:
The sample point value of the data phase in percent.
:raises ValueError:
if the arguments are invalid.
"""
if nom_sample_point < 50.0:
raise ValueError(
f"nom_sample_point (={nom_sample_point}) must not be below 50%."
)
if data_sample_point < 50.0:
raise ValueError(
f"data_sample_point (={data_sample_point}) must not be below 50%."
)
possible_solutions: List[BitTimingFd] = []
for nom_brp in range(1, 257):
nbt = round(int(f_clock / (nom_bitrate * nom_brp)))
if nbt < 8:
break
effective_nom_bitrate = f_clock / (nbt * nom_brp)
if abs(effective_nom_bitrate - nom_bitrate) > nom_bitrate / 256:
continue
nom_tseg1 = int(round(nom_sample_point / 100 * nbt)) - 1
# limit tseg1, so tseg2 is at least 1 TQ
nom_tseg1 = min(nom_tseg1, nbt - 2)
nom_tseg2 = nbt - nom_tseg1 - 1
nom_sjw = min(nom_tseg2, 128)
for data_brp in range(1, 257):
dbt = round(int(f_clock / (data_bitrate * data_brp)))
if dbt < 8:
break
effective_data_bitrate = f_clock / (dbt * data_brp)
if abs(effective_data_bitrate - data_bitrate) > data_bitrate / 256:
continue
data_tseg1 = int(round(data_sample_point / 100 * dbt)) - 1
# limit tseg1, so tseg2 is at least 1 TQ
data_tseg1 = min(data_tseg1, dbt - 2)
data_tseg2 = dbt - data_tseg1 - 1
data_sjw = min(data_tseg2, 16)
try:
bt = BitTimingFd(
f_clock=f_clock,
nom_brp=nom_brp,
nom_tseg1=nom_tseg1,
nom_tseg2=nom_tseg2,
nom_sjw=nom_sjw,
data_brp=data_brp,
data_tseg1=data_tseg1,
data_tseg2=data_tseg2,
data_sjw=data_sjw,
)
possible_solutions.append(bt)
except ValueError:
continue
if not possible_solutions:
raise ValueError("No suitable bit timings found.")
# prefer using the same prescaler for arbitration and data phase
same_prescaler = list(
filter(lambda x: x.nom_brp == x.data_brp, possible_solutions)
)
if same_prescaler:
possible_solutions = same_prescaler
# sort solutions
for key, reverse in (
# prefer low prescaler
(lambda x: x.nom_brp + x.data_brp, False),
# prefer same prescaler for arbitration and data
(lambda x: abs(x.nom_brp - x.data_brp), False),
# prefer low sample point deviation from requested values
(
lambda x: (
abs(x.nom_sample_point - nom_sample_point)
+ abs(x.data_sample_point - data_sample_point)
),
False,
),
):
possible_solutions.sort(key=key, reverse=reverse)
return possible_solutions[0]
@property
def f_clock(self) -> int:
"""The CAN system clock frequency in Hz."""
return self._data["f_clock"]
@property
def nom_bitrate(self) -> int:
"""Nominal (arbitration phase) bitrate."""
return int(round(self.f_clock / (self.nbt * self.nom_brp)))
@property
def nom_brp(self) -> int:
"""Prescaler value for the arbitration phase."""
return self._data["nom_brp"]
@property
def nom_tq(self) -> int:
"""Nominal time quantum in nanoseconds"""
return int(round(self.nom_brp / self.f_clock * 1e9))
@property
def nbt(self) -> int:
"""Number of time quanta in a bit of the arbitration phase."""
return 1 + self.nom_tseg1 + self.nom_tseg2
@property
def nom_tseg1(self) -> int:
"""Time segment 1 value of the arbitration phase.
This is the sum of the propagation time segment and the phase buffer segment 1.
"""
return self._data["nom_tseg1"]
@property
def nom_tseg2(self) -> int:
"""Time segment 2 value of the arbitration phase. Also known as phase buffer segment 2."""
return self._data["nom_tseg2"]
@property
def nom_sjw(self) -> int:
"""Synchronization jump width of the arbitration phase.
The phase buffer segments may be shortened or lengthened by this value.
"""
return self._data["nom_sjw"]
@property
def nom_sample_point(self) -> float:
"""Sample point of the arbitration phase in percent."""
return 100.0 * (1 + self.nom_tseg1) / (1 + self.nom_tseg1 + self.nom_tseg2)
@property
def data_bitrate(self) -> int:
"""Bitrate of the data phase in bit/s."""
return int(round(self.f_clock / (self.dbt * self.data_brp)))
@property
def data_brp(self) -> int:
"""Prescaler value for the data phase."""
return self._data["data_brp"]
@property
def data_tq(self) -> int:
"""Data time quantum in nanoseconds"""
return int(round(self.data_brp / self.f_clock * 1e9))
@property
def dbt(self) -> int:
"""Number of time quanta in a bit of the data phase."""
return 1 + self.data_tseg1 + self.data_tseg2
@property
def data_tseg1(self) -> int:
"""TSEG1 value of the data phase.
This is the sum of the propagation time segment and the phase buffer segment 1.
"""
return self._data["data_tseg1"]
@property
def data_tseg2(self) -> int:
"""TSEG2 value of the data phase. Also known as phase buffer segment 2."""
return self._data["data_tseg2"]
@property
def data_sjw(self) -> int:
"""Synchronization jump width of the data phase.
The phase buffer segments may be shortened or lengthened by this value.
"""
return self._data["data_sjw"]
@property
def data_sample_point(self) -> float:
"""Sample point of the data phase in percent."""
return 100.0 * (1 + self.data_tseg1) / (1 + self.data_tseg1 + self.data_tseg2)
def oscillator_tolerance(
self,
node_loop_delay_ns: float = 250.0,
bus_length_m: float = 10.0,
) -> float:
"""Oscillator tolerance in percent according to ISO 11898-1.
:param float node_loop_delay_ns:
Transceiver loop delay in nanoseconds.
:param float bus_length_m:
Bus length in meters.
"""
delay_per_meter = 5
bidirectional_propagation_delay_ns = 2 * (
node_loop_delay_ns + delay_per_meter * bus_length_m
)
prop_seg = math.ceil(bidirectional_propagation_delay_ns / self.nom_tq)
nom_phase_seg1 = self.nom_tseg1 - prop_seg
nom_phase_seg2 = self.nom_tseg2
data_phase_seg2 = self.data_tseg2
df_clock_list = [
_oscillator_tolerance_condition_1(nom_sjw=self.nom_sjw, nbt=self.nbt),
_oscillator_tolerance_condition_2(
nbt=self.nbt,
nom_phase_seg1=nom_phase_seg1,
nom_phase_seg2=nom_phase_seg2,
),
_oscillator_tolerance_condition_3(data_sjw=self.data_sjw, dbt=self.dbt),
_oscillator_tolerance_condition_4(
nom_phase_seg1=nom_phase_seg1,
nom_phase_seg2=nom_phase_seg2,
data_phase_seg2=data_phase_seg2,
nbt=self.nbt,
dbt=self.dbt,
data_brp=self.data_brp,
nom_brp=self.nom_brp,
),
_oscillator_tolerance_condition_5(
data_sjw=self.data_sjw,
data_brp=self.data_brp,
nom_brp=self.nom_brp,
data_phase_seg2=data_phase_seg2,
nom_phase_seg2=nom_phase_seg2,
nbt=self.nbt,
dbt=self.dbt,
),
]
return max(0.0, min(df_clock_list) * 100)
def recreate_with_f_clock(self, f_clock: int) -> "BitTimingFd":
"""Return a new :class:`~can.BitTimingFd` instance with the given *f_clock* but the same
bit rates and sample points.
:param int f_clock:
The CAN system clock frequency in Hz.
:raises ValueError:
if no suitable bit timings were found.
"""
# try the most simple solution first: another bitrate prescaler
try:
return BitTimingFd.from_bitrate_and_segments(
f_clock=f_clock,
nom_bitrate=self.nom_bitrate,
nom_tseg1=self.nom_tseg1,
nom_tseg2=self.nom_tseg2,
nom_sjw=self.nom_sjw,
data_bitrate=self.data_bitrate,
data_tseg1=self.data_tseg1,
data_tseg2=self.data_tseg2,
data_sjw=self.data_sjw,
)
except ValueError:
pass
# create a new timing instance with the same sample points
bt = BitTimingFd.from_sample_point(
f_clock=f_clock,
nom_bitrate=self.nom_bitrate,
nom_sample_point=self.nom_sample_point,
data_bitrate=self.data_bitrate,
data_sample_point=self.data_sample_point,
)
if (
abs(bt.nom_sample_point - self.nom_sample_point) > 1.0
or abs(bt.data_sample_point - self.data_sample_point) > 1.0
):
raise ValueError(
"f_clock change failed because of sample point discrepancy."
)
# adapt synchronization jump width, so it has the same size relative to bit time as self
nom_sjw = int(round(self.nom_sjw / self.nbt * bt.nbt))
nom_sjw = max(1, min(bt.nom_tseg2, nom_sjw))
bt._data["nom_sjw"] = nom_sjw # pylint: disable=protected-access
data_sjw = int(round(self.data_sjw / self.dbt * bt.dbt))
data_sjw = max(1, min(bt.data_tseg2, data_sjw))
bt._data["data_sjw"] = data_sjw # pylint: disable=protected-access
bt._validate() # pylint: disable=protected-access