diff --git a/can/bit_timing.py b/can/bit_timing.py index 4311ff9a4..41c132713 100644 --- a/can/bit_timing.py +++ b/can/bit_timing.py @@ -13,12 +13,12 @@ class BitTiming(Mapping[str, int]): 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) + can.BitTiming(f_clock=8_000_000, brp=1, tseg1=5, tseg2=2, 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 + f_clock=8_000_000, bitrate=1_000_000, tseg1=5, tseg2=2, sjw=1 ) It is also possible to specify BTR registers:: @@ -60,9 +60,11 @@ def __init__( with the last sample being taken in the edge between TSEG1 and TSEG2. Three samples should only be used for relatively slow baudrates. :param bool strict: - If True, restrict bit timings to the minimum required range as defined in - ISO 11898. This can be used to ensure compatibility across a wide variety - of CAN hardware. + If True, restrict bit timings to the minimum configuration ranges, which + every CAN controller compliant with ISO 11898-1 has to support, and + require a sample point of at least 50%. This can be used to ensure + compatibility across a wide variety of CAN hardware. If False, only the + structural requirements are checked. :raises ValueError: if the arguments are invalid. """ @@ -74,27 +76,30 @@ def __init__( "sjw": sjw, "nof_samples": nof_samples, } + self._validate() if strict: - self._validate() self._restrict_to_minimum_range() def _validate(self) -> None: - if not 1 <= self.brp <= 64: - raise ValueError(f"bitrate prescaler (={self.brp}) must be in [1...64].") + _validate_positive("f_clock", self.f_clock) + _validate_segments( + brp=self.brp, tseg1=self.tseg1, tseg2=self.tseg2, sjw=self.sjw + ) + + if self.nof_samples not in (1, 3): + raise ValueError("nof_samples must be 1 or 3") - if not 1 <= self.tseg1 <= 16: - raise ValueError(f"tseg1 (={self.tseg1}) must be in [1...16].") + def _restrict_to_minimum_range(self) -> None: + if not 2 <= self.tseg1 <= 16: + raise ValueError(f"tseg1 (={self.tseg1}) must be in [2...16].") - if not 1 <= self.tseg2 <= 8: - raise ValueError(f"tseg2 (={self.tseg2}) must be in [1...8].") + if not 2 <= self.tseg2 <= 8: + raise ValueError(f"tseg2 (={self.tseg2}) must be in [2...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})." - ) + _validate_sjw_with_prop_seg(sjw=self.sjw, tseg1=self.tseg1) if self.sample_point < 50.0: raise ValueError( @@ -102,10 +107,6 @@ def _validate(self) -> None: f"(sample_point={self.sample_point:.2f}%)." ) - if self.nof_samples not in (1, 3): - raise ValueError("nof_samples must be 1 or 3") - - def _restrict_to_minimum_range(self) -> None: if not 8 <= self.nbt <= 25: raise ValueError(f"nominal bit time (={self.nbt}) must be in [8...25].") @@ -149,12 +150,15 @@ def from_bitrate_and_segments( with the last sample being taken in the edge between TSEG1 and TSEG2. Three samples should only be used for relatively slow baudrates. :param bool strict: - If True, restrict bit timings to the minimum required range as defined in - ISO 11898. This can be used to ensure compatibility across a wide variety - of CAN hardware. + If True, restrict bit timings to the minimum configuration ranges, which + every CAN controller compliant with ISO 11898-1 has to support, and + require a sample point of at least 50%. This can be used to ensure + compatibility across a wide variety of CAN hardware. If False, only the + structural requirements are checked. :raises ValueError: if the arguments are invalid. """ + _validate_positive("bitrate", bitrate) try: brp = round(f_clock / (bitrate * (1 + tseg1 + tseg2))) except ZeroDivisionError: @@ -185,18 +189,22 @@ def from_registers( ) -> "BitTiming": """Create a :class:`~can.BitTiming` instance from registers btr0 and btr1. + The registers are expected in the SJA1000-compatible (82C200) layout. + A combined 16-bit value, as used e.g. by PCAN, can be split with + ``btr0, btr1 = divmod(value, 256)``. + :param int f_clock: The CAN system clock frequency in Hz. :param int btr0: - The BTR0 register value used by many CAN controllers. + The 8-bit BTR0 register value (0...255). :param int btr1: - The BTR1 register value used by many CAN controllers. + The 8-bit BTR1 register value (0...255). :raises ValueError: if the arguments are invalid. """ - if not 0 <= btr0 < 2**16: + if not 0 <= btr0 < 2**8: raise ValueError(f"Invalid btr0 value. ({btr0})") - if not 0 <= btr1 < 2**16: + if not 0 <= btr1 < 2**8: raise ValueError(f"Invalid btr1 value. ({btr1})") brp = (btr0 & 0x3F) + 1 @@ -219,21 +227,26 @@ def iterate_from_sample_point( ) -> Iterator["BitTiming"]: """Create a :class:`~can.BitTiming` iterator with all the solutions for a sample point. + All returned timings are valid in strict mode. + :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. + :param float sample_point: + The sample point value in percent, in the range [50...100). :raises ValueError: if the arguments are invalid. """ + _validate_positive("bitrate", bitrate) - if sample_point < 50.0: - raise ValueError(f"sample_point (={sample_point}) must not be below 50%.") + if not 50.0 <= sample_point < 100.0: + raise ValueError( + f"sample_point (={sample_point}) must be in the range [50...100)%." + ) for brp in range(1, 65): - nbt = int(f_clock / (bitrate * brp)) + nbt = round(f_clock / (bitrate * brp)) if nbt < 8: break @@ -242,11 +255,11 @@ def iterate_from_sample_point( continue tseg1 = round(sample_point / 100 * nbt) - 1 - # limit tseg1, so tseg2 is at least 1 TQ - tseg1 = min(tseg1, nbt - 2) + # limit tseg1, so tseg2 is at least 2 TQ + tseg1 = min(tseg1, nbt - 3) tseg2 = nbt - tseg1 - 1 - sjw = min(tseg2, 4) + sjw = min(tseg1 - 1, tseg2, 4) try: bt = BitTiming( @@ -268,7 +281,9 @@ def from_sample_point( """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 + sample point. If several solutions exist, the one with the most accurate + bitrate is preferred, then the one closest 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 @@ -278,14 +293,16 @@ def from_sample_point( The CAN system clock frequency in Hz. :param int bitrate: Bitrate in bit/s. - :param int sample_point: - The sample point value in percent. + :param float sample_point: + The sample point value in percent, in the range [50...100). :raises ValueError: if the arguments are invalid. """ - if sample_point < 50.0: - raise ValueError(f"sample_point (={sample_point}) must not be below 50%.") + if not 50.0 <= sample_point < 100.0: + raise ValueError( + f"sample_point (={sample_point}) must be in the range [50...100)%." + ) possible_solutions: list[BitTiming] = list( cls.iterate_from_sample_point(f_clock, bitrate, sample_point) @@ -294,16 +311,16 @@ def from_sample_point( 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] + # prefer the most accurate bitrate, then the lowest sample point deviation, + # then the lowest prescaler + return min( + possible_solutions, + key=lambda x: ( + abs(x.f_clock / (x.nbt * x.brp) - bitrate), + abs(x.sample_point - sample_point), + x.brp, + ), + ) @property def f_clock(self) -> int: @@ -363,12 +380,32 @@ def sample_point(self) -> float: @property def btr0(self) -> int: - """Bit timing register 0 for SJA1000.""" + """Bit timing register 0 for SJA1000. + + :raises ValueError: + if brp or sjw do not fit into the register. + """ + if self.brp > 64: + raise ValueError(f"brp (={self.brp}) cannot be encoded in BTR0 (max. 64).") + if self.sjw > 4: + raise ValueError(f"sjw (={self.sjw}) cannot be encoded in BTR0 (max. 4).") return (self.sjw - 1) << 6 | self.brp - 1 @property def btr1(self) -> int: - """Bit timing register 1 for SJA1000.""" + """Bit timing register 1 for SJA1000. + + :raises ValueError: + if tseg1 or tseg2 do not fit into the register. + """ + if self.tseg1 > 16: + raise ValueError( + f"tseg1 (={self.tseg1}) cannot be encoded in BTR1 (max. 16)." + ) + if self.tseg2 > 8: + raise ValueError( + f"tseg2 (={self.tseg2}) cannot be encoded in BTR1 (max. 8)." + ) sam = 1 if self.nof_samples == 3 else 0 return sam << 7 | (self.tseg2 - 1) << 4 | self.tseg1 - 1 @@ -383,13 +420,18 @@ def oscillator_tolerance( Transceiver loop delay in nanoseconds. :param float bus_length_m: Bus length in meters. + :returns: + The maximum permissible oscillator tolerance in percent. A value of 0.0 + means that the propagation delay does not fit into time segment 1. """ 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) + # use the exact time quantum, self.tq is rounded to integer nanoseconds + tq_ns = self.brp * 1_000_000_000 / self.f_clock + prop_seg = math.ceil(bidirectional_propagation_delay_ns / tq_ns) nom_phase_seg1 = self.tseg1 - prop_seg nom_phase_seg2 = self.tseg2 df_clock_list = [ @@ -435,13 +477,17 @@ def recreate_with_f_clock(self, f_clock: int) -> "BitTiming": ) # adapt synchronization jump width, so it has the same size relative to bit time as self sjw = round(self.sjw / self.nbt * bt.nbt) - sjw = max(1, min(4, bt.tseg2, sjw)) + sjw = max(1, min(4, bt.tseg1 - 1, 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: + try: + btr = f"{self.btr0:02X}{self.btr1:02X}h" + except ValueError: + btr = "n/a" segments = [ f"BR: {self.bitrate:_} bit/s", f"SP: {self.sample_point:.2f}%", @@ -449,7 +495,7 @@ def __str__(self) -> str: f"TSEG1: {self.tseg1}", f"TSEG2: {self.tseg2}", f"SJW: {self.sjw}", - f"BTR: {self.btr0:02X}{self.btr1:02X}h", + f"BTR: {btr}", f"CLK: {self.f_clock / 1e6:.0f}MHz", ] return ", ".join(segments) @@ -563,9 +609,11 @@ def __init__( # pylint: disable=too-many-arguments The Synchronization Jump Width for the data phase. This value determines the maximum number of time quanta that the controller can resynchronize every bit. :param bool strict: - If True, restrict bit timings to the minimum required range as defined in - ISO 11898. This can be used to ensure compatibility across a wide variety - of CAN hardware. + If True, restrict bit timings to the minimum configuration ranges, which + every CAN controller compliant with ISO 11898-1 has to support, and + require a sample point of at least 50%. This can be used to ensure + compatibility across a wide variety of CAN hardware. If False, only the + structural requirements are checked. :raises ValueError: if the arguments are invalid. """ @@ -585,20 +633,21 @@ def __init__( # pylint: disable=too-many-arguments self._restrict_to_minimum_range() def _validate(self) -> None: - for param, value in self._data.items(): - if value < 0: # type: ignore[operator] - err_msg = f"'{param}' (={value}) must not be negative." - raise ValueError(err_msg) - - if self.nom_brp < 1: - raise ValueError( - f"nominal bitrate prescaler (={self.nom_brp}) must be at least 1." - ) - - if self.data_brp < 1: - raise ValueError( - f"data bitrate prescaler (={self.data_brp}) must be at least 1." - ) + _validate_positive("f_clock", self.f_clock) + _validate_segments( + brp=self.nom_brp, + tseg1=self.nom_tseg1, + tseg2=self.nom_tseg2, + sjw=self.nom_sjw, + prefix="nom_", + ) + _validate_segments( + brp=self.data_brp, + tseg1=self.data_tseg1, + tseg2=self.data_tseg2, + sjw=self.data_sjw, + prefix="data_", + ) if self.data_bitrate < self.nom_bitrate: raise ValueError( @@ -606,37 +655,19 @@ def _validate(self) -> None: f"equal to nom_bitrate (={self.nom_bitrate})" ) - 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 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}%)." - ) - def _restrict_to_minimum_range(self) -> None: # restrict to minimum required range as defined in ISO 11898 + if not 1 <= self.nom_brp <= 32: + raise ValueError(f"nom_brp (={self.nom_brp}) must be in [1...32].") + + if not 1 <= self.data_brp <= 32: + raise ValueError(f"data_brp (={self.data_brp}) must be in [1...32].") + if not 8 <= self.nbt <= 80: raise ValueError(f"Nominal bit time (={self.nbt}) must be in [8...80]") if not 5 <= self.dbt <= 25: - raise ValueError(f"Nominal bit time (={self.dbt}) must be in [5...25]") + raise ValueError(f"Data bit time (={self.dbt}) must be in [5...25]") if not 1 <= self.data_tseg1 <= 16: raise ValueError(f"data_tseg1 (={self.data_tseg1}) must be in [1...16].") @@ -668,6 +699,22 @@ def _restrict_to_minimum_range(self) -> None: if not 1 <= self.nom_sjw <= 16: raise ValueError(f"nom_sjw (={self.nom_sjw}) must be in [1...16].") + _validate_sjw_with_prop_seg( + sjw=self.nom_sjw, tseg1=self.nom_tseg1, prefix="nom_" + ) + + 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( # pylint: disable=too-many-arguments cls, @@ -710,12 +757,16 @@ def from_bitrate_and_segments( # pylint: disable=too-many-arguments The Synchronization Jump Width for the data phase. This value determines the maximum number of time quanta that the controller can resynchronize every bit. :param bool strict: - If True, restrict bit timings to the minimum required range as defined in - ISO 11898. This can be used to ensure compatibility across a wide variety - of CAN hardware. + If True, restrict bit timings to the minimum configuration ranges, which + every CAN controller compliant with ISO 11898-1 has to support, and + require a sample point of at least 50%. This can be used to ensure + compatibility across a wide variety of CAN hardware. If False, only the + structural requirements are checked. :raises ValueError: if the arguments are invalid. """ + _validate_positive("nom_bitrate", nom_bitrate) + _validate_positive("data_bitrate", data_bitrate) try: nom_brp = round(f_clock / (nom_bitrate * (1 + nom_tseg1 + nom_tseg2))) data_brp = round(f_clock / (data_bitrate * (1 + data_tseg1 + data_tseg2))) @@ -760,33 +811,40 @@ def iterate_from_sample_point( ) -> Iterator["BitTimingFd"]: """Create an :class:`~can.BitTimingFd` iterator with all the solutions for a sample point. + All returned timings are valid in strict mode. + :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 float nom_sample_point: + The sample point value of the arbitration phase in percent, + in the range [50...100). :param int data_bitrate: Data bitrate in bit/s. - :param int data_sample_point: - The sample point value of the data phase in percent. + :param float data_sample_point: + The sample point value of the data phase in percent, + in the range [50...100). :raises ValueError: if the arguments are invalid. """ - if nom_sample_point < 50.0: + _validate_positive("nom_bitrate", nom_bitrate) + _validate_positive("data_bitrate", data_bitrate) + + if not 50.0 <= nom_sample_point < 100.0: raise ValueError( - f"nom_sample_point (={nom_sample_point}) must not be below 50%." + f"nom_sample_point (={nom_sample_point}) must be in the range [50...100)%." ) - if data_sample_point < 50.0: + if not 50.0 <= data_sample_point < 100.0: raise ValueError( - f"data_sample_point (={data_sample_point}) must not be below 50%." + f"data_sample_point (={data_sample_point}) must be in the range [50...100)%." ) sync_seg = 1 for nom_brp in range(1, 257): - nbt = int(f_clock / (nom_bitrate * nom_brp)) + nbt = round(f_clock / (nom_bitrate * nom_brp)) if nbt < 1: break @@ -799,10 +857,10 @@ def iterate_from_sample_point( nom_tseg1 = min(nom_tseg1, nbt - sync_seg - 2) nom_tseg2 = nbt - nom_tseg1 - 1 - nom_sjw = min(nom_tseg2, 128) + nom_sjw = min(nom_tseg1 - 1, nom_tseg2, 128) for data_brp in range(1, 257): - dbt = round(int(f_clock / (data_bitrate * data_brp))) + dbt = round(f_clock / (data_bitrate * data_brp)) if dbt < 1: break @@ -815,7 +873,9 @@ def iterate_from_sample_point( data_tseg1 = min(data_tseg1, dbt - sync_seg - 2) data_tseg2 = dbt - data_tseg1 - 1 - data_sjw = min(data_tseg2, 16) + # unlike the arbitration phase, the data phase may have no + # propagation segment, so SJW may be as large as data_tseg1 + data_sjw = min(data_tseg1, data_tseg2, 16) try: bt = BitTimingFd( @@ -846,7 +906,10 @@ def from_sample_point( """Create a :class:`~can.BitTimingFd` instance for a sample point. 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 + sample points. If several solutions exist, the one with the most accurate + bitrates is preferred, then one using the same prescaler for both phases, + then the one closest 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 @@ -856,23 +919,25 @@ def from_sample_point( 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 float nom_sample_point: + The sample point value of the arbitration phase in percent, + in the range [50...100). :param int data_bitrate: Data bitrate in bit/s. - :param int data_sample_point: - The sample point value of the data phase in percent. + :param float data_sample_point: + The sample point value of the data phase in percent, + in the range [50...100). :raises ValueError: if the arguments are invalid. """ - if nom_sample_point < 50.0: + if not 50.0 <= nom_sample_point < 100.0: raise ValueError( - f"nom_sample_point (={nom_sample_point}) must not be below 50%." + f"nom_sample_point (={nom_sample_point}) must be in the range [50...100)%." ) - if data_sample_point < 50.0: + if not 50.0 <= data_sample_point < 100.0: raise ValueError( - f"data_sample_point (={data_sample_point}) must not be below 50%." + f"data_sample_point (={data_sample_point}) must be in the range [50...100)%." ) possible_solutions: list[BitTimingFd] = list( @@ -888,31 +953,21 @@ def from_sample_point( 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, + # prefer the most accurate bitrates, then the same prescaler for arbitration + # and data phase (same time quantum, optimal clock tolerance), then the + # lowest sample point deviation, then low prescalers + return min( + possible_solutions, + key=lambda x: ( + abs(x.f_clock / (x.nbt * x.nom_brp) - nom_bitrate) / nom_bitrate + + abs(x.f_clock / (x.dbt * x.data_brp) - data_bitrate) / data_bitrate, + x.nom_brp != x.data_brp, + abs(x.nom_sample_point - nom_sample_point) + + abs(x.data_sample_point - data_sample_point), + abs(x.nom_brp - x.data_brp), + x.nom_brp + x.data_brp, ), - ): - possible_solutions.sort(key=key, reverse=reverse) - - return possible_solutions[0] + ) @property def f_clock(self) -> int: @@ -1022,13 +1077,18 @@ def oscillator_tolerance( Transceiver loop delay in nanoseconds. :param float bus_length_m: Bus length in meters. + :returns: + The maximum permissible oscillator tolerance in percent. A value of 0.0 + means that the propagation delay does not fit into time segment 1. """ 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) + # use the exact time quantum, self.nom_tq is rounded to integer nanoseconds + nom_tq_ns = self.nom_brp * 1_000_000_000 / self.f_clock + prop_seg = math.ceil(bidirectional_propagation_delay_ns / nom_tq_ns) nom_phase_seg1 = self.nom_tseg1 - prop_seg nom_phase_seg2 = self.nom_tseg2 @@ -1106,10 +1166,10 @@ def recreate_with_f_clock(self, f_clock: int) -> "BitTimingFd": ) # adapt synchronization jump width, so it has the same size relative to bit time as self nom_sjw = round(self.nom_sjw / self.nbt * bt.nbt) - nom_sjw = max(1, min(bt.nom_tseg2, nom_sjw)) + nom_sjw = max(1, min(bt.nom_tseg1 - 1, bt.nom_tseg2, nom_sjw)) bt._data["nom_sjw"] = nom_sjw # pylint: disable=protected-access data_sjw = round(self.data_sjw / self.dbt * bt.dbt) - data_sjw = max(1, min(bt.data_tseg2, data_sjw)) + data_sjw = max(1, min(bt.data_tseg1, bt.data_tseg2, data_sjw)) bt._data["data_sjw"] = data_sjw # pylint: disable=protected-access bt._validate() # pylint: disable=protected-access return bt @@ -1155,6 +1215,42 @@ def __hash__(self) -> int: return tuple(self._data.values()).__hash__() +def _validate_positive(name: str, value: int) -> None: + """Raise a :class:`ValueError` if *value* is not greater than zero.""" + if value <= 0: + raise ValueError(f"{name} (={value}) must be greater than 0.") + + +def _validate_segments( + brp: int, tseg1: int, tseg2: int, sjw: int, prefix: str = "" +) -> None: + """Check the structural requirements that every bit timing must fulfil.""" + for name, value in (("brp", brp), ("tseg1", tseg1), ("tseg2", tseg2), ("sjw", sjw)): + if value < 1: + raise ValueError(f"{prefix}{name} (={value}) must be at least 1.") + + # SJW must not exceed either phase buffer segment; Phase_Seg1 is part of tseg1 + for name, value in (("tseg1", tseg1), ("tseg2", tseg2)): + if sjw > value: + raise ValueError( + f"{prefix}sjw (={sjw}) must not be greater than " + f"{prefix}{name} (={value})." + ) + + +def _validate_sjw_with_prop_seg(sjw: int, tseg1: int, prefix: str = "") -> None: + """Check SJW against Phase_Seg1 for bit times with a propagation segment. + + In the nominal bit time, tseg1 contains at least one time quantum of + propagation segment, so Phase_Seg1 and therefore SJW is at most ``tseg1 - 1``. + """ + if sjw > tseg1 - 1: + raise ValueError( + f"{prefix}sjw (={sjw}) must be less than {prefix}tseg1 (={tseg1}), " + f"because {prefix}tseg1 contains at least one quantum of propagation segment." + ) + + def _oscillator_tolerance_condition_1(nom_sjw: int, nbt: int) -> float: """Arbitration phase - resynchronization""" return nom_sjw / (2 * 10 * nbt) diff --git a/can/cli.py b/can/cli.py index d0ff70126..e15e7d153 100644 --- a/can/cli.py +++ b/can/cli.py @@ -240,7 +240,7 @@ def __call__( ) from None if not (timing := _dict2timing(timing_dict)): - err_msg = "Invalid --timing argument. Incomplete parameters." + err_msg = "Invalid --timing argument. Incomplete or invalid parameters." raise argparse.ArgumentError(self, err_msg) setattr(namespace, self.dest, timing) diff --git a/can/util.py b/can/util.py index f3b1040fd..0fa4b9bfc 100644 --- a/can/util.py +++ b/can/util.py @@ -2,7 +2,6 @@ Utilities and configuration file parsing. """ -import contextlib import copy import functools import json @@ -253,9 +252,12 @@ def _create_bus_config(config: dict[str, Any]) -> typechecking.BusConfig: def _dict2timing(data: dict[str, Any]) -> BitTiming | BitTimingFd | None: """Try to instantiate a :class:`~can.BitTiming` or :class:`~can.BitTimingFd` from - a dictionary. Return `None` if not possible.""" + a dictionary. Return `None` if not possible. - with contextlib.suppress(ValueError, TypeError): + If all parameters are present but do not form a valid bit timing, a warning + is logged before returning `None`.""" + + try: if set(typechecking.BitTimingFdDict.__annotations__).issubset(data): return BitTimingFd( **{ @@ -264,7 +266,7 @@ def _dict2timing(data: dict[str, Any]) -> BitTiming | BitTimingFd | None: }, strict=False, ) - elif set(typechecking.BitTimingDict.__annotations__).issubset(data): + if set(typechecking.BitTimingDict.__annotations__).issubset(data): return BitTiming( **{ key: int(data[key]) @@ -272,6 +274,8 @@ def _dict2timing(data: dict[str, Any]) -> BitTiming | BitTimingFd | None: }, strict=False, ) + except (ValueError, TypeError) as exc: + log.warning("Ignoring invalid bit timing parameters: %s", exc) return None diff --git a/doc/bit_timing.rst b/doc/bit_timing.rst index bf7aad486..a7d6701ef 100644 --- a/doc/bit_timing.rst +++ b/doc/bit_timing.rst @@ -10,10 +10,15 @@ These parameters include: * **tseg1**: The time segment 1 (TSEG1) is the amount of time from the end of the sync segment until the sample point. It is expressed in time quanta (TQ). + TSEG1 is the sum of the propagation segment, which compensates for the signal + delays on the bus and in the transceivers, and the phase buffer segment 1. * **tseg2**: The time segment 2 (TSEG2) is the amount of time from the sample point until the end of the bit. It is expressed in TQ. + TSEG2 is also known as phase buffer segment 2. * **sjw**: The synchronization jump width (SJW) is the maximum number - of TQ that the controller can resynchronize every bit. + of TQ by which the controller can lengthen phase buffer segment 1 or + shorten phase buffer segment 2 to resynchronize. It must not be larger + than either phase buffer segment. * **sample point**: The sample point is defined as the point in time within a bit where the bus controller samples the bus for dominant or recessive levels. It is typically expressed as a percentage of the bit time. @@ -37,20 +42,28 @@ respectively. The sample point would be 6 TQ after the start of the bit, leaving 2 TQ for the information processing by the bus nodes. .. note:: - The values for TSEG1, TSEG2 and SJW are chosen such that the - sample point is at least 50% of the total bit time. This ensures that - there is sufficient time for the signal to stabilize before it is sampled. + The CAN standard does not restrict the position of the sample point. + However, a sample point below 50% leaves only a short phase buffer + segment 1 and therefore a small SJW, which reduces the tolerable deviation + of the oscillators. The sample point calculations of python-can and the + strict mode therefore require a sample point of at least 50%. Sample points + between 75% and 87.5% are common in practice. .. note:: In CAN FD, the arbitration (nominal) phase and the data phase can have different bit rates. As a result, there are two separate sample points to consider. +.. note:: + At high data bit rates, CAN FD controllers rely on transmitter delay + compensation. This mechanism can only be used with a data phase + prescaler (``data_brp``) of 1 or 2. + Another important parameter is **f_clock**: The CAN system clock frequency -in Hz. This frequency is used to derive the TQ size from the bit rate. -The relationship is ``f_clock = (tseg1+tseg2+1) * bitrate * brp``. -The bit rate prescaler value **brp** is usually determined by the controller -and is chosen to ensure that the resulting bit time is an integer value. +in Hz. The bit rate prescaler **brp** divides this frequency to derive the +TQ size. The relationship is ``f_clock = (tseg1+tseg2+1) * bitrate * brp``. +Since a bit consists of an integer number of TQ, brp, tseg1 and tseg2 have +to be chosen such that this relationship holds for the desired bit rate. Typical CAN clock frequencies are 8-80 MHz. In most cases, the recommended settings for a predefined set of common @@ -85,9 +98,52 @@ produce an overview of possible bit timings for your desired bit rate: BR: 250_000 bit/s, SP: 75.00%, BRP: 2, TSEG1: 11, TSEG2: 4, SJW: 4, BTR: C13Ah, CLK: 8MHz BR: 250_000 bit/s, SP: 81.25%, BRP: 2, TSEG1: 12, TSEG2: 3, SJW: 3, BTR: 812Bh, CLK: 8MHz BR: 250_000 bit/s, SP: 87.50%, BRP: 2, TSEG1: 13, TSEG2: 2, SJW: 2, BTR: 411Ch, CLK: 8MHz - BR: 250_000 bit/s, SP: 93.75%, BRP: 2, TSEG1: 14, TSEG2: 1, SJW: 1, BTR: 010Dh, CLK: 8MHz +Strict Mode +----------- + +Without strict mode, :class:`~can.BitTiming` and :class:`~can.BitTimingFd` +only check structural requirements: all prescalers and segments must be at +least 1 and SJW must not be larger than TSEG1 or TSEG2. Many CAN controllers +support much larger ranges than shown below. + +Passing ``strict=True`` restricts the bit timings to the minimum configuration +ranges, which every CAN controller compliant with ISO 11898-1 has to support. +This can be used to ensure compatibility across a wide variety of CAN hardware. +In strict mode, the sample point must also be at least 50%. The timings returned +by ``from_sample_point()`` and ``iterate_from_sample_point()`` always satisfy +strict mode. + +The strict ranges for CAN 2.0 (:class:`~can.BitTiming`) are: + +* **brp**: 1 to 32 +* **nominal bit time**: 8 to 25 TQ +* **tseg1**: 2 to 16 TQ +* **tseg2**: 2 to 8 TQ +* **sjw**: 1 to 4 TQ and less than tseg1, because tseg1 contains at least + one TQ of propagation segment +* **bitrate**: 5 kbit/s to 1 Mbit/s + +The strict ranges for CAN FD (:class:`~can.BitTimingFd`) are: + +* **nom_brp** and **data_brp**: 1 to 32 +* **nominal bit time**: 8 to 80 TQ +* **data bit time**: 5 to 25 TQ +* **nom_tseg1**: 2 to 128 TQ with a shared prescaler, 2 to 64 TQ with + separate prescalers +* **nom_tseg2**: 2 to 32 TQ with a shared prescaler, 2 to 16 TQ with + separate prescalers +* **nom_sjw**: 1 to 32 TQ with a shared prescaler, 1 to 16 TQ with + separate prescalers, and less than nom_tseg1 +* **data_tseg1**: 1 to 16 TQ, since the data phase may have no propagation + segment +* **data_tseg2**: 2 to 8 TQ +* **data_sjw**: 1 to 8 TQ + +Configuration +------------- + It is possible to specify CAN 2.0 bit timings using the config file: @@ -122,6 +178,8 @@ A :class:`dict` of the relevant config parameters can be easily obtained by call Check :doc:`configuration` for more information about saving and loading configurations. +Reference +--------- .. autoclass:: can.BitTiming :class-doc-from: both diff --git a/doc/changelog.d/2147.changed.rst b/doc/changelog.d/2147.changed.rst new file mode 100644 index 000000000..b1e57c36a --- /dev/null +++ b/doc/changelog.d/2147.changed.rst @@ -0,0 +1 @@ +``BitTiming`` and ``BitTimingFd`` now always validate the basic bit timing structure and refuse to encode out-of-range BTR registers, ``strict=True`` follows the minimum configuration ranges of ISO 11898-1, and ``from_sample_point()`` prefers the most accurate bitrate. diff --git a/test/test_bit_timing.py b/test/test_bit_timing.py index 514c31244..1cc3d06cf 100644 --- a/test/test_bit_timing.py +++ b/test/test_bit_timing.py @@ -60,47 +60,19 @@ def test_from_bitrate_and_segments(): timing = can.BitTiming.from_bitrate_and_segments( f_clock=8_000_000, bitrate=125_000, tseg1=11, tseg2=4, sjw=2, nof_samples=3 ) - assert timing.f_clock == 8_000_000 - assert timing.bitrate == 125_000 - assert timing.brp == 4 - assert timing.nbt == 16 - assert timing.tseg1 == 11 - assert timing.tseg2 == 4 - assert timing.sjw == 2 - assert timing.nof_samples == 3 - assert timing.sample_point == 75 - assert timing.btr0 == 0x43 - assert timing.btr1 == 0xBA + assert timing == can.BitTiming( + f_clock=8_000_000, brp=4, tseg1=11, tseg2=4, sjw=2, nof_samples=3 + ) timing = can.BitTiming.from_bitrate_and_segments( f_clock=8_000_000, bitrate=500_000, tseg1=13, tseg2=2, sjw=1 ) - assert timing.f_clock == 8_000_000 - assert timing.bitrate == 500_000 - assert timing.brp == 1 - assert timing.nbt == 16 - assert timing.tseg1 == 13 - assert timing.tseg2 == 2 - assert timing.sjw == 1 - assert timing.nof_samples == 1 - assert timing.sample_point == 87.5 - assert timing.btr0 == 0x00 - assert timing.btr1 == 0x1C + assert timing == can.BitTiming(f_clock=8_000_000, brp=1, tseg1=13, tseg2=2, sjw=1) timing = can.BitTiming.from_bitrate_and_segments( f_clock=8_000_000, bitrate=1_000_000, tseg1=5, tseg2=2, sjw=1, strict=True ) - assert timing.f_clock == 8_000_000 - assert timing.bitrate == 1_000_000 - assert timing.brp == 1 - assert timing.nbt == 8 - assert timing.tseg1 == 5 - assert timing.tseg2 == 2 - assert timing.sjw == 1 - assert timing.nof_samples == 1 - assert timing.sample_point == 75 - assert timing.btr0 == 0x00 - assert timing.btr1 == 0x14 + assert timing == can.BitTiming(f_clock=8_000_000, brp=1, tseg1=5, tseg2=2, sjw=1) timing = can.BitTimingFd.from_bitrate_and_segments( f_clock=80_000_000, @@ -113,38 +85,17 @@ def test_from_bitrate_and_segments(): data_tseg2=10, data_sjw=10, ) - - assert timing.f_clock == 80_000_000 - assert timing.nom_bitrate == 500_000 - assert timing.nom_brp == 1 - assert timing.nbt == 160 - assert timing.nom_tseg1 == 119 - assert timing.nom_tseg2 == 40 - assert timing.nom_sjw == 40 - assert timing.nom_sample_point == 75 - assert timing.f_clock == 80_000_000 - assert timing.data_bitrate == 2_000_000 - assert timing.data_brp == 1 - assert timing.dbt == 40 - assert timing.data_tseg1 == 29 - assert timing.data_tseg2 == 10 - assert timing.data_sjw == 10 - assert timing.data_sample_point == 75 - - # test strict invalid - with pytest.raises(ValueError): - can.BitTimingFd.from_bitrate_and_segments( - f_clock=80_000_000, - nom_bitrate=500_000, - nom_tseg1=119, - nom_tseg2=40, - nom_sjw=40, - data_bitrate=2_000_000, - data_tseg1=29, - data_tseg2=10, - data_sjw=10, - strict=True, - ) + assert timing == can.BitTimingFd( + f_clock=80_000_000, + nom_brp=1, + nom_tseg1=119, + nom_tseg2=40, + nom_sjw=40, + data_brp=1, + data_tseg1=29, + data_tseg2=10, + data_sjw=10, + ) def test_can_fd(): @@ -177,21 +128,6 @@ def test_can_fd(): assert timing.data_sjw == 10 assert timing.data_sample_point == 75 - # test strict invalid - with pytest.raises(ValueError): - can.BitTimingFd( - f_clock=80_000_000, - nom_brp=1, - nom_tseg1=119, - nom_tseg2=40, - nom_sjw=40, - data_brp=1, - data_tseg1=29, - data_tseg2=10, - data_sjw=10, - strict=True, - ) - # test strict valid timing = can.BitTimingFd( f_clock=80_000_000, @@ -222,17 +158,23 @@ def test_can_fd(): assert timing.data_sample_point == 75 -def test_from_btr(): - timing = can.BitTiming.from_registers(f_clock=8_000_000, btr0=0x00, btr1=0x14) - assert timing.bitrate == 1_000_000 - assert timing.brp == 1 - assert timing.nbt == 8 - assert timing.tseg1 == 5 - assert timing.tseg2 == 2 - assert timing.sjw == 1 - assert timing.sample_point == 75 - assert timing.btr0 == 0x00 - assert timing.btr1 == 0x14 +@pytest.mark.parametrize( + ("btr0", "btr1"), + [(0x100, 0x14), (0x00, 0x100), (-1, 0x14), (0x00, -1)], +) +def test_from_btr_out_of_range(btr0: int, btr1: int) -> None: + """ + Test Scope: + BitTiming.from_registers rejects register values that do not fit into 8 bits. + Preconditions: + None. + Events: + Call BitTiming.from_registers with btr0 or btr1 outside of 0...255. + Evaluate: + A ValueError is raised. + """ + with pytest.raises(ValueError): + can.BitTiming.from_registers(f_clock=8_000_000, btr0=btr0, btr1=btr1) def test_btr_persistence(): @@ -268,23 +210,6 @@ def test_from_sample_point(): assert fd_timing.data_bitrate == 8_000_000 assert 69 < fd_timing.data_sample_point < 71 - # check that there is a solution for every sample point - for sp in range(50, 100): - can.BitTiming.from_sample_point( - f_clock=16_000_000, bitrate=500_000, sample_point=sp - ) - - # check that there is a solution for every sample point - for nsp in range(50, 100): - for dsp in range(50, 100): - can.BitTimingFd.from_sample_point( - f_clock=80_000_000, - nom_bitrate=500_000, - nom_sample_point=nsp, - data_bitrate=2_000_000, - data_sample_point=dsp, - ) - def test_iterate_from_sample_point(): for sp in range(50, 100): @@ -297,8 +222,8 @@ def test_iterate_from_sample_point(): ) assert len(solutions) >= 2 - for nsp in range(50, 100): - for dsp in range(50, 100): + for nsp in range(50, 100, 7): + for dsp in range(50, 100, 7): solutions = list( can.BitTimingFd.iterate_from_sample_point( f_clock=80_000_000, @@ -420,16 +345,13 @@ def test_hash(): data_sjw=10, ), } + for timing in list(_timings): + assert type(timing)(**dict(timing)) in _timings def test_mapping(): timing = can.BitTiming(f_clock=8_000_000, brp=1, tseg1=5, tseg2=2, sjw=1) timing_dict = dict(timing) - assert timing_dict["f_clock"] == timing["f_clock"] - assert timing_dict["brp"] == timing["brp"] - assert timing_dict["tseg1"] == timing["tseg1"] - assert timing_dict["tseg2"] == timing["tseg2"] - assert timing_dict["sjw"] == timing["sjw"] assert timing == can.BitTiming(**timing_dict) fd_timing = can.BitTimingFd( @@ -444,15 +366,6 @@ def test_mapping(): data_sjw=10, ) fd_timing_dict = dict(fd_timing) - assert fd_timing_dict["f_clock"] == fd_timing["f_clock"] - assert fd_timing_dict["nom_brp"] == fd_timing["nom_brp"] - assert fd_timing_dict["nom_tseg1"] == fd_timing["nom_tseg1"] - assert fd_timing_dict["nom_tseg2"] == fd_timing["nom_tseg2"] - assert fd_timing_dict["nom_sjw"] == fd_timing["nom_sjw"] - assert fd_timing_dict["data_brp"] == fd_timing["data_brp"] - assert fd_timing_dict["data_tseg1"] == fd_timing["data_tseg1"] - assert fd_timing_dict["data_tseg2"] == fd_timing["data_tseg2"] - assert fd_timing_dict["data_sjw"] == fd_timing["data_sjw"] assert fd_timing == can.BitTimingFd(**fd_timing_dict) @@ -529,3 +442,430 @@ def test_recreate_with_f_clock(): assert (fd_timing_80mhz.data_sjw / fd_timing_80mhz.dbt) == pytest.approx( fd_timing_60mhz.data_sjw / fd_timing_60mhz.dbt, abs=1e-2 ) + + +_CLASSIC_KWARGS = {"f_clock": 8_000_000, "brp": 1, "tseg1": 5, "tseg2": 2, "sjw": 1} +_FD_KWARGS = { + "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, +} + + +@pytest.mark.parametrize( + ("cls", "base", "overrides", "match"), + [ + (can.BitTiming, _CLASSIC_KWARGS, {"f_clock": 0}, "f_clock"), + (can.BitTiming, _CLASSIC_KWARGS, {"brp": 0}, "brp"), + (can.BitTiming, _CLASSIC_KWARGS, {"tseg1": 0}, "tseg1"), + (can.BitTiming, _CLASSIC_KWARGS, {"tseg2": 0}, "tseg2"), + (can.BitTiming, _CLASSIC_KWARGS, {"sjw": 0}, "sjw"), + (can.BitTiming, _CLASSIC_KWARGS, {"sjw": 3}, "tseg2"), + (can.BitTiming, _CLASSIC_KWARGS, {"tseg1": 1, "tseg2": 4, "sjw": 2}, "tseg1"), + (can.BitTiming, _CLASSIC_KWARGS, {"nof_samples": 2}, "nof_samples"), + (can.BitTimingFd, _FD_KWARGS, {"f_clock": 0}, "f_clock"), + (can.BitTimingFd, _FD_KWARGS, {"nom_brp": 0}, "nom_brp"), + (can.BitTimingFd, _FD_KWARGS, {"nom_tseg2": 0}, "nom_tseg2"), + (can.BitTimingFd, _FD_KWARGS, {"nom_sjw": 21}, "nom_tseg2"), + (can.BitTimingFd, _FD_KWARGS, {"data_sjw": 0}, "data_sjw"), + ( + can.BitTimingFd, + _FD_KWARGS, + {"data_tseg1": 1, "data_tseg2": 8, "data_sjw": 2}, + "data_tseg1", + ), + ], +) +def test_invalid_structure(cls, base, overrides, match) -> None: + """ + Test Scope: + BitTiming and BitTimingFd reject structurally invalid parameters, + also when strict is False. + Preconditions: + A valid set of constructor arguments for the respective class. + Events: + Construct the class with one or more arguments replaced by an invalid value. + Evaluate: + A ValueError naming the offending parameter is raised. + """ + with pytest.raises(ValueError, match=match): + cls(**{**base, **overrides}) + + +@pytest.mark.parametrize( + ("overrides", "register"), + [ + ({"brp": 100}, "btr0"), + ({"tseg1": 10, "tseg2": 5, "sjw": 5}, "btr0"), + ({"tseg1": 20}, "btr1"), + ({"tseg1": 10, "tseg2": 9}, "btr1"), + ], +) +def test_btr_not_encodable(overrides, register) -> None: + """ + Test Scope: + A non-strict BitTiming with values beyond the SJA1000 register range + can be created, but cannot be converted to BTR registers. + Preconditions: + None. + Events: + Construct a non-strict BitTiming with brp, sjw, tseg1 or tseg2 out of + register range, read the register property and convert the timing to str. + Evaluate: + The register property raises a ValueError and the string representation + shows "BTR: n/a". + """ + timing = can.BitTiming(**{**_CLASSIC_KWARGS, **overrides}) + with pytest.raises(ValueError): + getattr(timing, register) + assert "BTR: n/a" in str(timing) + + +@pytest.mark.parametrize( + "create", + [ + lambda: can.BitTiming.from_bitrate_and_segments( + f_clock=8_000_000, bitrate=0, tseg1=5, tseg2=2, sjw=1 + ), + lambda: can.BitTiming.from_sample_point(f_clock=8_000_000, bitrate=-1), + lambda: list( + can.BitTiming.iterate_from_sample_point(f_clock=8_000_000, bitrate=0) + ), + lambda: can.BitTimingFd.from_bitrate_and_segments( + f_clock=80_000_000, + nom_bitrate=0, + nom_tseg1=59, + nom_tseg2=20, + nom_sjw=10, + data_bitrate=8_000_000, + data_tseg1=6, + data_tseg2=3, + data_sjw=2, + ), + lambda: can.BitTimingFd.from_sample_point( + f_clock=80_000_000, + nom_bitrate=500_000, + nom_sample_point=80.0, + data_bitrate=-1, + data_sample_point=80.0, + ), + lambda: list( + can.BitTimingFd.iterate_from_sample_point( + f_clock=80_000_000, + nom_bitrate=0, + nom_sample_point=80.0, + data_bitrate=2_000_000, + data_sample_point=80.0, + ) + ), + ], + ids=[ + "from_bitrate_and_segments", + "from_sample_point", + "iterate_from_sample_point", + "fd_from_bitrate_and_segments", + "fd_from_sample_point", + "fd_iterate_from_sample_point", + ], +) +def test_invalid_bitrate(create) -> None: + """ + Test Scope: + The factory methods and solvers reject bitrates that are not positive. + Preconditions: + None. + Events: + Call a factory method or solver with a bitrate of 0 or below. + Evaluate: + A ValueError naming the bitrate is raised. + """ + with pytest.raises(ValueError, match="bitrate"): + create() + + +@pytest.mark.parametrize( + ("cls", "base", "overrides", "match"), + [ + (can.BitTiming, _CLASSIC_KWARGS, {"tseg1": 1, "tseg2": 6}, "tseg1"), + (can.BitTiming, _CLASSIC_KWARGS, {"tseg1": 6, "tseg2": 1}, "tseg2"), + ( + can.BitTiming, + _CLASSIC_KWARGS, + {"tseg1": 2, "tseg2": 5, "sjw": 2}, + "propagation", + ), + (can.BitTiming, _CLASSIC_KWARGS, {"tseg1": 2, "tseg2": 5}, "sample point"), + ( + can.BitTiming, + _CLASSIC_KWARGS, + {"f_clock": 264_000_000, "brp": 33}, + "prescaler", + ), + (can.BitTimingFd, _FD_KWARGS, {"nom_brp": 33, "data_brp": 33}, "nom_brp"), + ( + can.BitTimingFd, + _FD_KWARGS, + {"nom_tseg1": 119, "nom_tseg2": 40, "nom_sjw": 40}, + "Nominal bit time", + ), + (can.BitTimingFd, _FD_KWARGS, {"nom_brp": 32, "data_brp": 33}, "data_brp"), + ( + can.BitTimingFd, + _FD_KWARGS, + {"nom_tseg1": 10, "nom_tseg2": 10, "nom_sjw": 10}, + "propagation", + ), + ( + can.BitTimingFd, + _FD_KWARGS, + {"nom_tseg1": 9, "nom_tseg2": 12, "nom_sjw": 5}, + "arbitration sample point", + ), + ( + can.BitTimingFd, + _FD_KWARGS, + {"data_tseg1": 2, "data_tseg2": 5, "data_sjw": 2}, + "data sample point", + ), + ], +) +def test_strict_ranges(cls, base, overrides, match) -> None: + """ + Test Scope: + With strict=True, BitTiming and BitTimingFd reject timings outside the + minimum configuration ranges of ISO 11898-1 and sample points below 50%. + Preconditions: + A set of constructor arguments that is valid in strict mode. + Events: + Construct the class with strict=True and one or more arguments replaced + by a value outside of the strict range. + Evaluate: + A ValueError naming the violated rule is raised. + """ + with pytest.raises(ValueError, match=match): + cls(**{**base, **overrides}, strict=True) + + +@pytest.mark.parametrize( + ("cls", "kwargs", "sample_point_attr"), + [ + (can.BitTiming, {**_CLASSIC_KWARGS, "tseg1": 2, "tseg2": 5}, "sample_point"), + ( + can.BitTimingFd, + {**_FD_KWARGS, "nom_tseg1": 9, "nom_tseg2": 12, "nom_sjw": 5}, + "nom_sample_point", + ), + ( + can.BitTimingFd, + {**_FD_KWARGS, "data_tseg1": 2, "data_tseg2": 5, "data_sjw": 2}, + "data_sample_point", + ), + ], +) +def test_non_strict_allows_low_sample_point(cls, kwargs, sample_point_attr) -> None: + """ + Test Scope: + Without strict mode, sample points below 50% are accepted, since + ISO 11898-1 does not restrict the position of the sample point. + Preconditions: + None. + Events: + Construct the class with strict=False and segments that place the + sample point below 50%. + Evaluate: + The instance is created and reports the sample point below 50%. + """ + timing = cls(**kwargs) + assert getattr(timing, sample_point_attr) < 50.0 + + +def test_from_sample_point_follows_strict_rules() -> None: + """ + Test Scope: + The solvers only return timings that fulfil the strict rules for + tseg2 and SJW, also when the requested sample point cannot be reached. + Preconditions: + None. + Events: + Call BitTiming.from_sample_point for sample points from 50% to 99% and + BitTimingFd.from_sample_point for sample points from 50% to 99% in steps of 7%. + Evaluate: + tseg2 is at least 2 for classic CAN and SJW is less than tseg1 for + classic CAN and the arbitration phase of CAN FD. + """ + for sp in range(50, 100): + timing = can.BitTiming.from_sample_point( + f_clock=8_000_000, bitrate=1_000_000, sample_point=sp + ) + assert timing.tseg2 >= 2 + assert timing.sjw <= timing.tseg1 - 1 + + for sp in range(50, 100, 7): + fd_timing = can.BitTimingFd.from_sample_point( + f_clock=80_000_000, + nom_bitrate=500_000, + nom_sample_point=sp, + data_bitrate=2_000_000, + data_sample_point=sp, + ) + assert fd_timing.nom_sjw <= fd_timing.nom_tseg1 - 1 + + +def test_from_sample_point_prefers_accurate_bitrate() -> None: + """ + Test Scope: + BitTiming.from_sample_point finds solutions whose prescaler and bit time + only match the requested bitrate within the tolerance, and prefers an + exact bitrate over a closer sample point. + Preconditions: + None. + Events: + Request 12 kbit/s and 20 kbit/s from an 8 MHz clock. + Evaluate: + A 12 kbit/s timing within the tolerance of 1/256 is found. The 20 kbit/s + timing matches the requested bitrate exactly, although another candidate + is closer to the requested sample point. + """ + timing = can.BitTiming.from_sample_point( + f_clock=8_000_000, bitrate=12_000, sample_point=75.0 + ) + assert abs(timing.bitrate - 12_000) <= 12_000 / 256 + + candidates = list( + can.BitTiming.iterate_from_sample_point( + f_clock=8_000_000, bitrate=20_000, sample_point=61.0 + ) + ) + timing = can.BitTiming.from_sample_point( + f_clock=8_000_000, bitrate=20_000, sample_point=61.0 + ) + assert timing.f_clock / (timing.nbt * timing.brp) == 20_000 + assert any( + abs(c.sample_point - 61.0) < abs(timing.sample_point - 61.0) for c in candidates + ) + + +@pytest.mark.parametrize("sample_point", [100.0, 150.0]) +@pytest.mark.parametrize( + "create", + [ + lambda sp: can.BitTiming.from_sample_point( + f_clock=8_000_000, bitrate=500_000, sample_point=sp + ), + lambda sp: list( + can.BitTiming.iterate_from_sample_point( + f_clock=8_000_000, bitrate=500_000, sample_point=sp + ) + ), + lambda sp: can.BitTimingFd.from_sample_point( + f_clock=80_000_000, + nom_bitrate=500_000, + nom_sample_point=sp, + data_bitrate=2_000_000, + data_sample_point=80.0, + ), + lambda sp: list( + can.BitTimingFd.iterate_from_sample_point( + f_clock=80_000_000, + nom_bitrate=500_000, + nom_sample_point=80.0, + data_bitrate=2_000_000, + data_sample_point=sp, + ) + ), + ], + ids=[ + "from_sample_point", + "iterate_from_sample_point", + "fd_from_sample_point", + "fd_iterate_from_sample_point", + ], +) +def test_sample_point_too_high(create, sample_point) -> None: + """ + Test Scope: + The solvers reject sample points of 100% or more. + Preconditions: + None. + Events: + Call a solver with a sample point of 100% or above. + Evaluate: + A ValueError naming the sample point is raised. + """ + with pytest.raises(ValueError, match="sample_point"): + create(sample_point) + + +def test_oscillator_tolerance_exact_time_quantum() -> None: + """ + Test Scope: + BitTiming.oscillator_tolerance uses the exact time quantum, also when it + is not an integer number of nanoseconds. + Preconditions: + None. + Events: + Calculate the oscillator tolerance of an 80 MHz timing with brp=1 + (time quantum 12.5 ns), tseg1=63, tseg2=16 and sjw=16 for a node loop + delay of 250 ns and a bus length of 10 m. + Evaluate: + The round trip delay of 600 ns needs 48 time quanta of propagation + segment, leaving Phase_Seg1 = 15. The limiting condition is then + min(Phase_Seg1, Phase_Seg2) / (2 * (13 * nbt - Phase_Seg2)) = 15 / 2048. + """ + timing = can.BitTiming(f_clock=80_000_000, brp=1, tseg1=63, tseg2=16, sjw=16) + osc_tol = timing.oscillator_tolerance(node_loop_delay_ns=250, bus_length_m=10.0) + assert osc_tol == pytest.approx(100 * 15 / 2048) + + +def test_fd_from_sample_point_prefers_accurate_bitrate() -> None: + """ + Test Scope: + BitTimingFd.from_sample_point prefers an accurate bitrate over a shared + prescaler, and a shared prescaler over a closer sample point. + Preconditions: + None. + Events: + Request 250 kbit/s / 1.212121 Mbit/s from an 80 MHz clock, where only + separate prescalers give an exact nominal bitrate. Request 125 kbit/s / + 1 Mbit/s from a 20 MHz clock, where separate prescalers would reach the + requested sample points more closely. + Evaluate: + The first timing has the exact nominal bitrate. The second timing uses + the same prescaler for both phases, although an exact candidate with + separate prescalers is closer to the requested sample points. + """ + timing = can.BitTimingFd.from_sample_point( + f_clock=80_000_000, + nom_bitrate=250_000, + nom_sample_point=80.0, + data_bitrate=1_212_121, + data_sample_point=75.0, + ) + assert timing.f_clock / (timing.nbt * timing.nom_brp) == 250_000 + + args = { + "f_clock": 20_000_000, + "nom_bitrate": 125_000, + "nom_sample_point": 75.0, + "data_bitrate": 1_000_000, + "data_sample_point": 75.0, + } + timing = can.BitTimingFd.from_sample_point(**args) + assert timing.nom_brp == timing.data_brp + + def sample_point_deviation(t: can.BitTimingFd) -> float: + return abs(t.nom_sample_point - 75.0) + abs(t.data_sample_point - 75.0) + + assert any( + c.nom_brp != c.data_brp + and c.nom_bitrate == 125_000 + and c.data_bitrate == 1_000_000 + and sample_point_deviation(c) < sample_point_deviation(timing) + for c in can.BitTimingFd.iterate_from_sample_point(**args) + ) diff --git a/test/test_util.py b/test/test_util.py index 53a9c973b..73994ae42 100644 --- a/test/test_util.py +++ b/test/test_util.py @@ -182,6 +182,35 @@ def test_bit_timing_cfg(self): assert timing.tseg2 == 2 assert timing.sjw == 1 + def test_invalid_bit_timing_cfg_logs_warning(self): + """ + Test Scope: + A config with complete but invalid bit timing parameters is not + silently ignored. + Preconditions: + None. + Events: + Create a bus config with all CAN 2.0 bit timing parameters, where + sjw is greater than tseg2. + Evaluate: + The config contains no timing and a warning naming the invalid + parameter is logged. + """ + with self.assertLogs("can.util", level="WARNING") as logs: + can_cfg = _create_bus_config( + { + **self.base_config, + "f_clock": "8000000", + "brp": "1", + "tseg1": "5", + "tseg2": "2", + "sjw": "3", + "nof_samples": "1", + } + ) + assert "timing" not in can_cfg + assert "sjw" in logs.output[0] + def test_bit_timing_fd_cfg(self): canfd_cfg = _create_bus_config( {