diff --git a/can/bridge.py b/can/bridge.py index 57ebb368d..2ebdff9f8 100644 --- a/can/bridge.py +++ b/can/bridge.py @@ -9,7 +9,7 @@ import errno import sys import time -from datetime import datetime +from datetime import datetime, timezone from typing import Final from can.cli import add_bus_arguments, create_bus_from_namespace @@ -52,14 +52,14 @@ def main() -> None: reader1_to_2 = RedirectReader(bus2) reader2_to_1 = RedirectReader(bus1) with Notifier(bus1, [reader1_to_2]), Notifier(bus2, [reader2_to_1]): - print(f"CAN Bridge (Started on {datetime.now()})") + print(f"CAN Bridge (Started on {datetime.now(tz=timezone.utc)})") try: while True: time.sleep(1) except KeyboardInterrupt: pass - print(f"CAN Bridge (Stopped on {datetime.now()})") + print(f"CAN Bridge (Stopped on {datetime.now(tz=timezone.utc)})") if __name__ == "__main__": diff --git a/can/broadcastmanager.py b/can/broadcastmanager.py index 1fea9ac50..c79fffdb6 100644 --- a/can/broadcastmanager.py +++ b/can/broadcastmanager.py @@ -108,7 +108,8 @@ def __init__(self, messages: Sequence[Message] | Message, period: float) -> None The messages to be sent periodically. :param period: The rate in seconds at which to send the messages. - :raises ValueError: If the given messages are invalid + :raises TypeError: If messages is not a message, list, or tuple + :raises ValueError: If the messages are empty or otherwise invalid """ messages = self._check_and_convert_messages(messages) @@ -130,15 +131,16 @@ def _check_and_convert_messages( Should be called when the cyclic task is initialized. - :raises ValueError: If the given messages are invalid + :raises TypeError: If messages is not a message or sequence + :raises ValueError: If the messages are empty or otherwise invalid """ - if not isinstance(messages, (list, tuple)): + if not isinstance(messages, Sequence): if isinstance(messages, Message): messages = [messages] else: - raise ValueError("Must be either a list, tuple, or a Message") + raise TypeError("Must be either a sequence of messages or a Message") if not messages: - raise ValueError("Must be at least a list or tuple of length 1") + raise ValueError("Must be a sequence of length at least 1") messages = tuple(messages) all_same_id = all( @@ -172,7 +174,8 @@ def __init__( Approximate duration in seconds to continue sending messages. If no duration is provided, the task will continue indefinitely. - :raises ValueError: If the given messages are invalid + :raises TypeError: If messages is not a message, list, or tuple + :raises ValueError: If the messages are empty or otherwise invalid """ super().__init__(messages, period) self.duration = duration @@ -197,7 +200,7 @@ def _check_modified_messages(self, messages: tuple[Message, ...]) -> None: Should be called when modify_data is called in the cyclic task. - :raises ValueError: If the given messages are invalid + :raises ValueError: If the number or arbitration ID of messages changes """ if len(self.messages) != len(messages): raise ValueError( @@ -223,7 +226,8 @@ def modify_data(self, messages: Sequence[Message] | Message) -> None: to the original number of messages originally specified for this task. - :raises ValueError: If the given messages are invalid + :raises TypeError: If messages is not a message or sequence + :raises ValueError: If the messages are empty or otherwise invalid """ messages = self._check_and_convert_messages(messages) self._check_modified_messages(messages) @@ -252,7 +256,8 @@ def __init__( :param initial_period: :param subsequent_period: - :raises ValueError: If the given messages are invalid + :raises TypeError: If messages is not a message or sequence + :raises ValueError: If the messages are empty or otherwise invalid """ super().__init__(messages, subsequent_period) self._channel = channel @@ -287,7 +292,8 @@ def __init__( it shall return either ``True`` or ``False`` depending on desired behaviour of `ThreadBasedCyclicSendTask`. - :raises ValueError: If the given messages are invalid + :raises TypeError: If messages is not a message or sequence + :raises ValueError: If the messages are empty or otherwise invalid """ super().__init__(messages, period, duration) self.bus = bus @@ -362,12 +368,12 @@ def _run(self) -> None: # Prevent calling bus.send from multiple threads self.bus.send(self.messages[msg_index]) except Exception as exc: # pylint: disable=broad-except - log.exception(exc) + log.exception("Cyclic send task failed") # stop if `on_error` callback was not given if self.on_error is None: self.stop() - raise exc + raise # stop if `on_error` returns False if not self.on_error(exc): diff --git a/can/bus.py b/can/bus.py index 03425caaa..7de26103e 100644 --- a/can/bus.py +++ b/can/bus.py @@ -4,6 +4,7 @@ import contextlib import logging +import sys import threading from abc import ABC, abstractmethod from collections.abc import Callable, Iterator, Sequence @@ -14,7 +15,10 @@ cast, ) -from typing_extensions import Self +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self import can.typechecking from can.broadcastmanager import CyclicSendTaskABC, ThreadBasedCyclicSendTask @@ -239,6 +243,8 @@ def send_periodic( A started task instance. Note the task can be stopped (and depending on the backend modified) by calling the task's :meth:`~can.broadcastmanager.CyclicTask.stop` method. + :raises TypeError: If `msgs` is neither a message nor a sequence of messages + :raises ValueError: If `msgs` is an empty sequence .. note:: @@ -257,11 +263,10 @@ def send_periodic( if isinstance(msgs, Message): msgs = [msgs] elif isinstance(msgs, Sequence): - # A Sequence does not necessarily provide __bool__ we need to use len() if len(msgs) == 0: - raise ValueError("Must be a sequence at least of length 1") + raise ValueError("Must be a sequence of length at least 1") else: - raise ValueError("Must be either a message or a sequence of messages") + raise TypeError("Must be either a message or a sequence of messages") # Create a backend specific task; will be patched to a _SelfRemovingCyclicTask later task = cast( @@ -438,9 +443,8 @@ def _matches_filters(self, msg: Message) -> bool: for _filter in self._filters: # check if this filter even applies to the message - if "extended" in _filter: - if _filter["extended"] != msg.is_extended_id: - continue + if "extended" in _filter and _filter["extended"] != msg.is_extended_id: + continue # then check for the mask and id can_id = _filter["can_id"] diff --git a/can/interface.py b/can/interface.py index efde5b214..69112fa4d 100644 --- a/can/interface.py +++ b/can/interface.py @@ -40,7 +40,7 @@ def _get_class_for_interface(interface: str) -> type[BusABC]: # Import the correct interface module try: module = importlib.import_module(module_name) - except Exception as e: + except Exception as e: # noqa: BLE001 raise CanInterfaceNotImplementedError( f"Cannot import module {module_name} for CAN interface '{interface}': {e}" ) from None @@ -48,7 +48,7 @@ def _get_class_for_interface(interface: str) -> type[BusABC]: # Get the correct class try: bus_class = getattr(module, class_name) - except Exception as e: + except AttributeError as e: raise CanInterfaceNotImplementedError( f"Cannot import class {class_name} from module {module_name} for CAN interface " f"'{interface}': {e}" @@ -140,7 +140,7 @@ def Bus( # noqa: N802 def detect_available_configs( - interfaces: None | str | Iterable[str] = None, + interfaces: str | Iterable[str] | None = None, timeout: float = 5.0, ) -> Sequence[AutoDetectedConfig]: """Detect all configurations/channels that the interfaces could diff --git a/can/interfaces/cantact.py b/can/interfaces/cantact.py index 332a7e234..7b11df614 100644 --- a/can/interfaces/cantact.py +++ b/can/interfaces/cantact.py @@ -42,7 +42,7 @@ def _detect_available_configs() -> Sequence[AutoDetectedConfig]: return [] channels: list[AutoDetectedConfig] = [] - for i in range(0, interface.channel_count()): + for i in range(interface.channel_count()): channels.append({"interface": "cantact", "channel": f"ch:{i}"}) return channels diff --git a/can/interfaces/ics_neovi/__init__.py b/can/interfaces/ics_neovi/__init__.py index 74cb43af4..c1fefa7c1 100644 --- a/can/interfaces/ics_neovi/__init__.py +++ b/can/interfaces/ics_neovi/__init__.py @@ -1,4 +1,4 @@ -""" """ +"""ICS NeoVI CAN interface.""" __all__ = [ "ICSApiError", diff --git a/can/interfaces/ics_neovi/neovi_bus.py b/can/interfaces/ics_neovi/neovi_bus.py index 815ed6fa0..444f8f300 100644 --- a/can/interfaces/ics_neovi/neovi_bus.py +++ b/can/interfaces/ics_neovi/neovi_bus.py @@ -234,12 +234,9 @@ def __init__(self, channel, can_filters=None, **kwargs): for channel in self.channels: ics.set_bit_rate(self.dev, kwargs.get("bitrate"), channel) - if is_fd: - if "data_bitrate" in kwargs: - for channel in self.channels: - ics.set_fd_bit_rate( - self.dev, kwargs.get("data_bitrate"), channel - ) + if is_fd and "data_bitrate" in kwargs: + for channel in self.channels: + ics.set_fd_bit_rate(self.dev, kwargs.get("data_bitrate"), channel) except ics.RuntimeError as re: logger.error(re) err = ICSInitializationError(*ics.get_last_api_error(self.dev)) @@ -304,7 +301,7 @@ def _detect_available_configs(): try: devices = ics.find_devices() - except Exception as e: + except Exception as e: # noqa: BLE001 logger.debug("Failed to detect configs: %s", e) return [] diff --git a/can/interfaces/ixxat/canlib_vcinpl.py b/can/interfaces/ixxat/canlib_vcinpl.py index c6c924d8c..f29efe225 100644 --- a/can/interfaces/ixxat/canlib_vcinpl.py +++ b/can/interfaces/ixxat/canlib_vcinpl.py @@ -56,7 +56,7 @@ if sys.platform == "win32" or sys.platform == "cygwin": try: _canlib = CLibrary("vcinpl.dll") - except Exception as e: + except OSError as e: log.warning("Cannot load IXXAT vcinpl library: %s", e) else: # Will not work on other systems, but have it importable anyway for @@ -349,7 +349,7 @@ def __check_status(result, function, args): except AttributeError: # In case _canlib == None meaning we're not on win32/no lib found pass -except Exception as e: +except Exception as e: # noqa: BLE001 log.warning("Could not initialize IXXAT VCI library: %s", e) # --------------------------------------------------------------------------- @@ -742,10 +742,12 @@ def _recv_internal(self, timeout): raise VCIErrorLimitExceededError("Error warning limit exceeded") # Not checking CAN_STATUS_OVRRUN here because it is handled above and would be # raised every time as the flag is never cleared until a reset. - elif error_byte_2 > constants.CAN_STATUS_ININIT: + elif ( + error_byte_2 > constants.CAN_STATUS_ININIT + and error_byte_2 & constants.CAN_STATUS_BUSCERR + ): # CAN_STATUS_BUSCERR = 0x20 # bus coupling error - if error_byte_2 & constants.CAN_STATUS_BUSCERR: - raise VCIBusCouplingError("Bus coupling error") + raise VCIBusCouplingError("Bus coupling error") if not data_received: # Timed out / can message type is not DATA @@ -1005,7 +1007,7 @@ def _detect_available_configs() -> Sequence["AutoDetectedIxxatConfig"]: constants.FALSE, ctypes.byref(channel_handle), ) - except Exception: + except VCIError: # Array outside of bounds error == accessing a channel not in the hardware break else: diff --git a/can/interfaces/ixxat/canlib_vcinpl2.py b/can/interfaces/ixxat/canlib_vcinpl2.py index f74d4cece..8e94cf5be 100644 --- a/can/interfaces/ixxat/canlib_vcinpl2.py +++ b/can/interfaces/ixxat/canlib_vcinpl2.py @@ -53,7 +53,7 @@ if sys.platform == "win32" or sys.platform == "cygwin": try: _canlib = CLibrary("vcinpl2.dll") - except Exception as e: + except OSError as e: log.warning("Cannot load IXXAT vcinpl library: %s", e) else: # Will not work on other systems, but have it importable anyway for @@ -376,7 +376,7 @@ def __check_status(result, function, args): except AttributeError: # In case _canlib == None meaning we're not on win32/no lib found pass -except Exception as e: +except Exception as e: # noqa: BLE001 log.warning("Could not initialize IXXAT VCI library: %s", e) # --------------------------------------------------------------------------- diff --git a/can/interfaces/kvaser/__init__.py b/can/interfaces/kvaser/__init__.py index 7cfb13d8d..44e8da883 100644 --- a/can/interfaces/kvaser/__init__.py +++ b/can/interfaces/kvaser/__init__.py @@ -1,4 +1,4 @@ -""" """ +"""Kvaser CAN interface and CANlib bindings.""" __all__ = [ "CANLIBInitializationError", diff --git a/can/interfaces/kvaser/canlib.py b/can/interfaces/kvaser/canlib.py index 4403b60ca..7df8329d0 100644 --- a/can/interfaces/kvaser/canlib.py +++ b/can/interfaces/kvaser/canlib.py @@ -337,7 +337,7 @@ def init_kvaser_library(): log.debug("Initializing Kvaser CAN library") canInitializeLibrary() log.debug("CAN library initialized") - except Exception: + except CANLIBError: log.warning("Kvaser canlib could not be initialized.") @@ -614,7 +614,7 @@ def _update_timestamp_offset(self) -> float: kvReadTimer(self._read_handle, ctypes.byref(timer)) return time.time() - (timer.value * TIMESTAMP_FACTOR) - except Exception as exc: + except CANLIBError as exc: # timer is usually close to 0 log.info(str(exc)) return time.time() - (timer.value * TIMESTAMP_FACTOR) @@ -791,7 +791,7 @@ def _detect_available_configs(): num_channels = ctypes.c_int(0) canGetNumberOfChannels(ctypes.byref(num_channels)) - for channel in range(0, int(num_channels.value)): + for channel in range(int(num_channels.value)): info = get_channel_info(channel) config_list.append({"interface": "kvaser", "channel": channel, **info}) diff --git a/can/interfaces/nican.py b/can/interfaces/nican.py index ba5b991c9..ea567f4bb 100644 --- a/can/interfaces/nican.py +++ b/can/interfaces/nican.py @@ -134,7 +134,7 @@ def get_error_message(status_code: int) -> str: if sys.platform == "win32": try: nican = ctypes.windll.LoadLibrary("nican") - except Exception as e: + except OSError as e: nican = None logger.error("Failed to load NI-CAN driver: %s", e) else: diff --git a/can/interfaces/nixnet.py b/can/interfaces/nixnet.py index ec303a364..24157d032 100644 --- a/can/interfaces/nixnet.py +++ b/can/interfaces/nixnet.py @@ -33,7 +33,7 @@ import nixnet.constants # type: ignore import nixnet.system # type: ignore import nixnet.types # type: ignore -except Exception as exc: +except ImportError as exc: logger.warning("Could not import nixnet: %s", exc) @@ -345,7 +345,7 @@ def _detect_available_configs() -> list[can.typechecking.AutoDetectedConfig]: is nixnet.constants.CanTcvrCap.HS, # type: ignore[union-attr] } ) - except Exception as error: + except Exception as error: # noqa: BLE001 logger.debug("An error occured while searching for configs: %s", str(error)) return configs # type: ignore diff --git a/can/interfaces/pcan/__init__.py b/can/interfaces/pcan/__init__.py index a3eafcb4d..f0805b7e0 100644 --- a/can/interfaces/pcan/__init__.py +++ b/can/interfaces/pcan/__init__.py @@ -1,4 +1,4 @@ -""" """ +"""PCAN CAN interface and driver bindings.""" __all__ = [ "PcanBus", diff --git a/can/interfaces/pcan/pcan.py b/can/interfaces/pcan/pcan.py index a2f5f361f..a11a7fa6c 100644 --- a/can/interfaces/pcan/pcan.py +++ b/can/interfaces/pcan/pcan.py @@ -112,7 +112,7 @@ import select HAS_EVENTS = True - except Exception: + except ImportError: pass diff --git a/can/interfaces/robotell.py b/can/interfaces/robotell.py index c90faec29..a412fa939 100644 --- a/can/interfaces/robotell.py +++ b/can/interfaces/robotell.py @@ -245,7 +245,7 @@ def _readmessage(self, flushold, cfgchannel, timeout): # check to see if we have a complete packet in the RX buffer termpos = self._rxbuffer.find(terminator) - if headpos == 0 and termpos > headpos: + if headpos == 0 and termpos > headpos: # pylint: disable=chained-comparison # copy packet into message structure and un-escape bytes newmsg = bytearray() idx = headpos + len(header) diff --git a/can/interfaces/socketcan/socketcan.py b/can/interfaces/socketcan/socketcan.py index eaced1e0b..ef5e666e4 100644 --- a/can/interfaces/socketcan/socketcan.py +++ b/can/interfaces/socketcan/socketcan.py @@ -57,7 +57,7 @@ def bcm_header_factory( ): curr_stride = 0 results: list[ - tuple[str, type[ctypes.c_uint8] | type[ctypes.c_uint32] | type[ctypes.c_long]] + tuple[str, type[ctypes.c_uint8 | ctypes.c_uint32 | ctypes.c_long]] ] = [] pad_index = 0 for field in fields: diff --git a/can/interfaces/socketcand/socketcand.py b/can/interfaces/socketcand/socketcand.py index d401102f7..ae92e4cd9 100644 --- a/can/interfaces/socketcand/socketcand.py +++ b/can/interfaces/socketcand/socketcand.py @@ -196,7 +196,7 @@ def connect_to_server(s, host, port): try: s.connect((host, port)) return - except Exception as e: + except OSError as e: log.warning(f"Failed to connect to server: {type(e)} Message: {e}") now = time.time() * 1000 raise TimeoutError( @@ -368,6 +368,6 @@ def shutdown(self): def _detect_available_configs() -> list[can.typechecking.AutoDetectedConfig]: try: return detect_beacon() - except Exception as e: + except OSError as e: log.warning(f"Could not detect socketcand beacon: {e}") return [] diff --git a/can/interfaces/systec/ucan.py b/can/interfaces/systec/ucan.py index f969532d7..d1e51da91 100644 --- a/can/interfaces/systec/ucan.py +++ b/can/interfaces/systec/ucan.py @@ -313,7 +313,7 @@ def check_result(result, func, arguments): _UCAN_INITIALIZED = True - except Exception as ex: + except (AttributeError, OSError) as ex: log.warning("Cannot load SYSTEC ucan library: %s.", ex) diff --git a/can/interfaces/systec/ucanbus.py b/can/interfaces/systec/ucanbus.py index 00f101e4e..f5558b5fe 100644 --- a/can/interfaces/systec/ucanbus.py +++ b/can/interfaces/systec/ucanbus.py @@ -33,9 +33,10 @@ def can_msg_received_event(self, channel): def read_can_msg(self, channel, count, timeout): self._msg_received_event.clear() - if self.get_msg_pending(channel, PendingFlags.PENDING_FLAG_RX_DLL) == 0: - if not self._msg_received_event.wait(timeout): - return None, False + if self.get_msg_pending( + channel, PendingFlags.PENDING_FLAG_RX_DLL + ) == 0 and not self._msg_received_event.wait(timeout): + return None, False return super().read_can_msg(channel, 1) @@ -103,8 +104,8 @@ def __init__(self, channel, can_filters=None, **kwargs): """ try: self._ucan = Ucan() - except CanError as error: - raise error + except CanError: + raise except Exception as exception: raise CanInitializationError( "The SYSTEC ucan library has not been initialized." @@ -234,7 +235,7 @@ def _detect_available_configs(): "device_number": hw_info_ex.device_number, } ) - except Exception: + except (NameError, UcanException): log.warning("The SYSTEC ucan library has not been initialized.") return configs @@ -329,5 +330,5 @@ def shutdown(self): super().shutdown() try: self._ucan.shutdown() - except Exception as exception: + except UcanException as exception: log.error(exception) diff --git a/can/interfaces/udp_multicast/bus.py b/can/interfaces/udp_multicast/bus.py index 01f67bd8e..3747f3700 100644 --- a/can/interfaces/udp_multicast/bus.py +++ b/can/interfaces/udp_multicast/bus.py @@ -286,7 +286,7 @@ def _create_socket(self, address_family: socket.AddressFamily) -> socket.socket: ): # It is unavailable on macOS (ENOPROTOOPT) or windows(EINVAL/WSAEINVAL) self.timestamp_nanosecond = False else: - raise error + raise else: self.timestamp_nanosecond = True diff --git a/can/interfaces/usb2can/__init__.py b/can/interfaces/usb2can/__init__.py index f818130ee..2ae696ed8 100644 --- a/can/interfaces/usb2can/__init__.py +++ b/can/interfaces/usb2can/__init__.py @@ -1,4 +1,4 @@ -""" """ +"""USB2CAN CAN interface.""" __all__ = [ "Usb2CanAbstractionLayer", diff --git a/can/interfaces/usb2can/serial_selector.py b/can/interfaces/usb2can/serial_selector.py index 18ad3f873..d77c873c9 100644 --- a/can/interfaces/usb2can/serial_selector.py +++ b/can/interfaces/usb2can/serial_selector.py @@ -1,4 +1,4 @@ -""" """ +"""Discover USB2CAN devices and select them by serial number.""" import logging diff --git a/can/interfaces/usb2can/usb2canabstractionlayer.py b/can/interfaces/usb2can/usb2canabstractionlayer.py index 9fbf5c15c..25ceee6db 100644 --- a/can/interfaces/usb2can/usb2canabstractionlayer.py +++ b/can/interfaces/usb2can/usb2canabstractionlayer.py @@ -121,7 +121,7 @@ def __init__(self, dll: StringPathLike = "usb2can.dll") -> None: try: self.__m_dllBasic = windll.LoadLibrary(dll) if self.__m_dllBasic is None: - raise Exception("__m_dllBasic is None") + raise can.CanInitializationError("__m_dllBasic is None") except Exception as error: message = f"DLL failed to load at path: {dll}" diff --git a/can/interfaces/vector/__init__.py b/can/interfaces/vector/__init__.py index e78783f1f..29e963b93 100644 --- a/can/interfaces/vector/__init__.py +++ b/can/interfaces/vector/__init__.py @@ -1,4 +1,4 @@ -""" """ +"""Vector CAN interface and XL Driver bindings.""" __all__ = [ "VectorBus", diff --git a/can/interfaces/vector/canlib.py b/can/interfaces/vector/canlib.py index 8bdd77b83..799b5ac8e 100644 --- a/can/interfaces/vector/canlib.py +++ b/can/interfaces/vector/canlib.py @@ -69,14 +69,12 @@ class VectorBus(BusABC): @deprecated_args_alias( deprecation_start="4.0.0", deprecation_end="5.0.0", - **{ - "sjwAbr": "sjw_abr", - "tseg1Abr": "tseg1_abr", - "tseg2Abr": "tseg2_abr", - "sjwDbr": "sjw_dbr", - "tseg1Dbr": "tseg1_dbr", - "tseg2Dbr": "tseg2_dbr", - }, + sjwAbr="sjw_abr", + tseg1Abr="tseg1_abr", + tseg2Abr="tseg2_abr", + sjwDbr="sjw_dbr", + tseg1Dbr="tseg1_dbr", + tseg2Dbr="tseg2_dbr", ) def __init__( self, diff --git a/can/io/asc.py b/can/io/asc.py index 93ed79c35..36e395612 100644 --- a/can/io/asc.py +++ b/can/io/asc.py @@ -348,26 +348,25 @@ class ASCWriter(TextIOMessageWriter): """ FORMAT_MESSAGE = "{channel} {id:<15} {dir:<4} {dtype} {data}" - FORMAT_MESSAGE_FD = " ".join( - [ - "CANFD", - "{channel:>3}", - "{dir:<4}", - "{id:>8} {symbolic_name:>32}", - "{brs}", - "{esi}", - "{dlc:x}", - "{data_length:>2}", - "{data}", - "{message_duration:>8}", - "{message_length:>4}", - "{flags:>8X}", - "{crc:>8}", - "{bit_timing_conf_arb:>8}", - "{bit_timing_conf_data:>8}", - "{bit_timing_conf_ext_arb:>8}", - "{bit_timing_conf_ext_data:>8}", - ] + FORMAT_MESSAGE_FD = ( + "CANFD " + "{channel:>3} " + "{dir:<4} " + "{id:>8} " + "{symbolic_name:>32} " + "{brs} " + "{esi} " + "{dlc:x} " + "{data_length:>2} " + "{data} " + "{message_duration:>8} " + "{message_length:>4} " + "{flags:>8X} " + "{crc:>8} " + "{bit_timing_conf_arb:>8} " + "{bit_timing_conf_data:>8} " + "{bit_timing_conf_ext_arb:>8} " + "{bit_timing_conf_ext_data:>8}" ) FORMAT_DATE = "%a %b %d %H:%M:%S.{} %Y" FORMAT_EVENT = "{timestamp: 9.6f} {message}\n" diff --git a/can/io/generic.py b/can/io/generic.py index bda4e1cce..3870bbe66 100644 --- a/can/io/generic.py +++ b/can/io/generic.py @@ -8,6 +8,7 @@ import locale import os +import sys from abc import ABC, abstractmethod from collections.abc import Iterable from contextlib import AbstractContextManager @@ -24,7 +25,10 @@ TypeVar, ) -from typing_extensions import Self +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self from ..listener import Listener from ..message import Message @@ -137,7 +141,7 @@ def __init__( if isinstance(file, (str, os.PathLike)): encoding: str = kwargs.get("encoding", locale.getpreferredencoding(False)) # pylint: disable=consider-using-with - self.file = Path(file).open(mode=mode, encoding=encoding) + self.file = Path(file).open(mode=mode, encoding=encoding) # noqa: SIM115 else: self.file = file @@ -158,7 +162,7 @@ def __init__( # pylint: disable=unused-argument ) -> None: if isinstance(file, (str, os.PathLike)): # pylint: disable=consider-using-with,unspecified-encoding - self.file = Path(file).open(mode=mode) + self.file = Path(file).open(mode=mode) # noqa: SIM115 else: self.file = file @@ -232,7 +236,7 @@ def __init__( if isinstance(file, (str, os.PathLike)): encoding: str = kwargs.get("encoding", locale.getpreferredencoding(False)) # pylint: disable=consider-using-with - self.file = Path(file).open(mode=mode, encoding=encoding) + self.file = Path(file).open(mode=mode, encoding=encoding) # noqa: SIM115 else: self.file = file @@ -253,6 +257,6 @@ def __init__( # pylint: disable=unused-argument ) -> None: if isinstance(file, (str, os.PathLike)): # pylint: disable=consider-using-with,unspecified-encoding - self.file = Path(file).open(mode=mode) + self.file = Path(file).open(mode=mode) # noqa: SIM115 else: self.file = file diff --git a/can/io/logger.py b/can/io/logger.py index 5009c9756..04c93e04e 100644 --- a/can/io/logger.py +++ b/can/io/logger.py @@ -5,9 +5,10 @@ import gzip import os import pathlib +import sys from abc import ABC, abstractmethod from collections.abc import Callable -from datetime import datetime +from datetime import datetime, timezone from types import TracebackType from typing import ( Any, @@ -16,7 +17,10 @@ Literal, ) -from typing_extensions import Self +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self from .._entry_points import read_entry_points from ..message import Message @@ -402,7 +406,7 @@ def _default_name(self) -> StringPathLike: new_name = ( path.stem.split(".")[0] + "_" - + datetime.now().strftime("%Y-%m-%dT%H%M%S") + + datetime.now(tz=timezone.utc).strftime("%Y-%m-%dT%H%M%S") + "_" + f"#{self.rollover_count:03}" + "".join(path.suffixes[-2:]) diff --git a/can/io/mf4.py b/can/io/mf4.py index fcde2e193..e6dcd2f35 100644 --- a/can/io/mf4.py +++ b/can/io/mf4.py @@ -9,7 +9,7 @@ import heapq import logging from collections.abc import Generator, Iterator -from datetime import datetime +from datetime import datetime, timezone from hashlib import md5 from io import BufferedIOBase, BytesIO from pathlib import Path @@ -124,7 +124,7 @@ def __init__( ) super().__init__(file, mode="w+b") - now = datetime.now() + now = datetime.now(tz=timezone.utc) self._mdf = cast("MDF4", MDF(version="4.10")) self._mdf.header.start_time = now self.last_timestamp = self._start_time = now.timestamp() @@ -311,7 +311,7 @@ def _get_data(self, current_offset: int) -> Signal: return data_raw @abc.abstractmethod - def __iter__(self) -> Generator[Message, None, None]: + def __iter__(self) -> Iterator[Message]: pass diff --git a/can/io/trc.py b/can/io/trc.py index c02bdcfe9..c9c315b6e 100644 --- a/can/io/trc.py +++ b/can/io/trc.py @@ -112,13 +112,11 @@ def _extract_header(self) -> str: else: break - if self.file_version >= TRCFileVersion.V1_1: - if self._start_time is None: - raise ValueError("File has no start time information") + if self.file_version >= TRCFileVersion.V1_1 and self._start_time is None: + raise ValueError("File has no start time information") - if self.file_version >= TRCFileVersion.V2_0: - if not self.columns: - raise ValueError("File has no column information") + if self.file_version >= TRCFileVersion.V2_0 and not self.columns: + raise ValueError("File has no column information") if self.file_version == TRCFileVersion.UNKNOWN: logger.info( diff --git a/can/listener.py b/can/listener.py index 1e289bea6..285fca585 100644 --- a/can/listener.py +++ b/can/listener.py @@ -3,12 +3,18 @@ """ import asyncio +import sys import warnings from abc import ABC, abstractmethod from collections.abc import AsyncIterator from queue import Empty, SimpleQueue from typing import Any +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self + from can.bus import BusABC from can.message import Message @@ -165,7 +171,7 @@ async def get_message(self) -> Message: """ return await self.buffer.get() - def __aiter__(self) -> AsyncIterator[Message]: + def __aiter__(self) -> Self: return self async def __anext__(self) -> Message: diff --git a/can/logger.py b/can/logger.py index 537356643..e072eb6cb 100644 --- a/can/logger.py +++ b/can/logger.py @@ -1,7 +1,7 @@ import argparse import errno import sys -from datetime import datetime +from datetime import datetime, timezone from typing import ( TYPE_CHECKING, ) @@ -107,7 +107,7 @@ def main() -> None: bus.state = BusState.PASSIVE print(f"Connected to {bus.__class__.__name__}: {bus.channel_info}") - print(f"Can Logger (Started on {datetime.now()})") + print(f"Can Logger (Started on {datetime.now(tz=timezone.utc)})") logger: MessageWriter | BaseRotatingLogger if results.file_size: diff --git a/can/player.py b/can/player.py index 6190a58d8..51231f3d1 100644 --- a/can/player.py +++ b/can/player.py @@ -9,7 +9,7 @@ import errno import math import sys -from datetime import datetime +from datetime import datetime, timezone from typing import TYPE_CHECKING, cast from can import LogReader, MessageSync @@ -38,7 +38,7 @@ def _parse_loop(value: str) -> int | float: raise argparse.ArgumentTypeError(err_msg) from exc -def _format_player_start_message(iteration: int, loop_count: int | float) -> str: +def _format_player_start_message(iteration: int, loop_count: float) -> str: """ Generate a status message indicating the start of a CAN log replay iteration. @@ -54,7 +54,7 @@ def _format_player_start_message(iteration: int, loop_count: int | float) -> str else: loop_val = "∞" if math.isinf(loop_count) else str(loop_count) loop_info = f" [loop {iteration + 1}/{loop_val}]" - return f"Can LogReader (Started on {datetime.now()}){loop_info}" + return f"Can LogReader (Started on {datetime.now(tz=timezone.utc)}){loop_info}" def main() -> None: diff --git a/can/util.py b/can/util.py index 42ae8dc5f..765c9c9dc 100644 --- a/can/util.py +++ b/can/util.py @@ -237,9 +237,8 @@ def _create_bus_config(config: dict[str, Any]) -> typechecking.BusConfig: if not 0 < port < 65535: raise ValueError("Port config must be inside 0-65535 range!") - if "timing" not in config: - if timing := _dict2timing(config): - config["timing"] = timing + if "timing" not in config and (timing := _dict2timing(config)): + config["timing"] = timing if "fd" in config: config["fd"] = config["fd"] not in (0, False) diff --git a/can/viewer.py b/can/viewer.py index 8d9d228bb..d9958abf9 100644 --- a/can/viewer.py +++ b/can/viewer.py @@ -140,11 +140,10 @@ def run(self): if self.scroll > 0: self.scroll -= 1 self.redraw_screen() - elif key == curses.KEY_DOWN: + elif key == curses.KEY_DOWN and self.scroll <= len(self.ids) - self.y + 1: # Limit scrolling, so the maximum scrolling position is one below the last line - if self.scroll <= len(self.ids) - self.y + 1: - self.scroll += 1 - self.redraw_screen() + self.scroll += 1 + self.redraw_screen() # Check if screen was resized resized = curses.is_term_resized(self.y, self.x) diff --git a/doc/changelog.d/2126.changed.rst b/doc/changelog.d/2126.changed.rst new file mode 100644 index 000000000..15c64c9e8 --- /dev/null +++ b/doc/changelog.d/2126.changed.rst @@ -0,0 +1 @@ +``can.BusABC.send_periodic()`` may raise a ``TypeError`` now if the msgs argument is not a message or a sequence of messages. diff --git a/doc/conf.py b/doc/conf.py old mode 100755 new mode 100644 diff --git a/examples/cyclic_checksum.py b/examples/cyclic_checksum.py old mode 100644 new mode 100755 index 763fcd72b..79ca8fcd3 --- a/examples/cyclic_checksum.py +++ b/examples/cyclic_checksum.py @@ -58,6 +58,8 @@ def compute_xbr_checksum(message: can.Message, counter: int) -> int: if __name__ == "__main__": - with can.Bus(channel=0, interface="virtual", receive_own_messages=True) as _bus: - with can.Notifier(bus=_bus, listeners=[print]): - cyclic_checksum_send(_bus) + with ( + can.Bus(channel=0, interface="virtual", receive_own_messages=True) as _bus, + can.Notifier(bus=_bus, listeners=[print]), + ): + cyclic_checksum_send(_bus) diff --git a/examples/serial_com.py b/examples/serial_com.py index 9f203b2e0..08b8eb589 100755 --- a/examples/serial_com.py +++ b/examples/serial_com.py @@ -48,30 +48,32 @@ def receive(bus, stop_event): def main(): """Controls the sender and receiver.""" - with can.Bus(interface="serial", channel="/dev/ttyS10") as server: - with can.Bus(interface="serial", channel="/dev/ttyS11") as client: - tx_msg = can.Message( - arbitration_id=0x01, - data=[0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88], - ) - - # Thread for sending and receiving messages - stop_event = threading.Event() - t_send_cyclic = threading.Thread( - target=send_cyclic, args=(server, tx_msg, stop_event) - ) - t_receive = threading.Thread(target=receive, args=(client, stop_event)) - t_receive.start() - t_send_cyclic.start() - - try: - while True: - time.sleep(0) # yield - except KeyboardInterrupt: - pass # exit normally - - stop_event.set() - time.sleep(0.5) + with ( + can.Bus(interface="serial", channel="/dev/ttyS10") as server, + can.Bus(interface="serial", channel="/dev/ttyS11") as client, + ): + tx_msg = can.Message( + arbitration_id=0x01, + data=[0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88], + ) + + # Thread for sending and receiving messages + stop_event = threading.Event() + t_send_cyclic = threading.Thread( + target=send_cyclic, args=(server, tx_msg, stop_event) + ) + t_receive = threading.Thread(target=receive, args=(client, stop_event)) + t_receive.start() + t_send_cyclic.start() + + try: + while True: + time.sleep(0) # yield + except KeyboardInterrupt: + pass # exit normally + + stop_event.set() + time.sleep(0.5) print("Stopped script") diff --git a/examples/simple_log_converter.py b/examples/simple_log_converter.py index 20e8fba75..bbe3fd177 100755 --- a/examples/simple_log_converter.py +++ b/examples/simple_log_converter.py @@ -15,10 +15,9 @@ def main(): """The transcoder""" - with can.LogReader(sys.argv[1]) as reader: - with can.Logger(sys.argv[2]) as writer: - for msg in reader: - writer.on_message_received(msg) + with can.LogReader(sys.argv[1]) as reader, can.Logger(sys.argv[2]) as writer: + for msg in reader: + writer.on_message_received(msg) if __name__ == "__main__": diff --git a/pyproject.toml b/pyproject.toml index 6694cc2bc..3c2a93bc3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -90,10 +90,10 @@ docs = [ "furo", ] lint = [ - "pylint==4.0.*", - "ruff==0.15.*", - "black==26.5.*", - "mypy==2.1.*", + "pylint==4.1.*", + "ruff==0.17.*", + "black==26.10.*", + "mypy==2.4.*", ] test = [ "pytest==9.0.*", @@ -200,6 +200,7 @@ known-first-party = ["can"] [tool.pylint] extension-pkg-allow-list = ["curses"] disable = [ + "abstract-method", "cyclic-import", "duplicate-code", "fixme", diff --git a/test/test_cyclic_socketcan.py b/test/test_cyclic_socketcan.py index 86f1c82dd..81855beb9 100644 --- a/test/test_cyclic_socketcan.py +++ b/test/test_cyclic_socketcan.py @@ -221,7 +221,7 @@ def test_cyclic_initializer_message(self): self.assertEqual(tx_message.is_fd, rx_message.is_fd) def test_cyclic_initializer_invalid_none(self): - with self.assertRaises(ValueError): + with self.assertRaises(TypeError): task = self._send_bus.send_periodic(None, self.PERIOD) def test_cyclic_initializer_invalid_empty_list(self): @@ -515,7 +515,7 @@ def test_modify_data_invalid(self): time.sleep(2 * self.PERIOD) - with self.assertRaises(ValueError): + with self.assertRaises(TypeError): task.modify_data(None) def test_modify_data_unequal_lengths(self): diff --git a/tox.ini b/tox.ini index ca02beb28..1d9d4cdc3 100644 --- a/tox.ini +++ b/tox.ini @@ -23,7 +23,7 @@ extras = commands = pytest {posargs} -[testenv:py314] +[testenv:py315] extras = canalystii mf4 @@ -31,9 +31,9 @@ extras = gs-usb pywin32 serial - # still no windows-curses for py314 + # still no windows-curses for py315 -[testenv:{py313t,py314t,pypy310,pypy311}] +[testenv:{py313t,py314t,py315t,pypy310,pypy311,pypy312}] extras = canalystii gs-usb @@ -41,7 +41,7 @@ extras = [testenv:docs] description = Build and test the documentation -basepython = py313 +basepython = py314 dependency_groups = docs extras = @@ -53,7 +53,7 @@ commands = [testenv:lint] description = Run linters -basepython = py313 +basepython = py314 dependency_groups = lint extras = @@ -81,7 +81,7 @@ commands = [testenv:type] description = Run type checker -basepython = py313 +basepython = py314 dependency_groups = lint extras = @@ -91,6 +91,7 @@ commands = mypy --python-version 3.12 . mypy --python-version 3.13 . mypy --python-version 3.14 . + mypy --python-version 3.15 . [pytest] testpaths = test