Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions can/bridge.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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__":
Expand Down
30 changes: 18 additions & 12 deletions can/broadcastmanager.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand All @@ -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(
Expand Down Expand Up @@ -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
Expand All @@ -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(
Expand All @@ -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)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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):
Expand Down
18 changes: 11 additions & 7 deletions can/bus.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import contextlib
import logging
import sys
import threading
from abc import ABC, abstractmethod
from collections.abc import Callable, Iterator, Sequence
Expand All @@ -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
Expand Down Expand Up @@ -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::

Expand All @@ -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(
Expand Down Expand Up @@ -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"]
Expand Down
6 changes: 3 additions & 3 deletions can/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,15 +40,15 @@ 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

# 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}"
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion can/interfaces/cantact.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion can/interfaces/ics_neovi/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
""" """
"""ICS NeoVI CAN interface."""

__all__ = [
"ICSApiError",
Expand Down
11 changes: 4 additions & 7 deletions can/interfaces/ics_neovi/neovi_bus.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down Expand Up @@ -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 []

Expand Down
14 changes: 8 additions & 6 deletions can/interfaces/ixxat/canlib_vcinpl.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
# ---------------------------------------------------------------------------

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
4 changes: 2 additions & 2 deletions can/interfaces/ixxat/canlib_vcinpl2.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
# ---------------------------------------------------------------------------

Expand Down
2 changes: 1 addition & 1 deletion can/interfaces/kvaser/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
""" """
"""Kvaser CAN interface and CANlib bindings."""

__all__ = [
"CANLIBInitializationError",
Expand Down
6 changes: 3 additions & 3 deletions can/interfaces/kvaser/canlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.")


Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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})
Expand Down
2 changes: 1 addition & 1 deletion can/interfaces/nican.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
4 changes: 2 additions & 2 deletions can/interfaces/nixnet.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)


Expand Down Expand Up @@ -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
2 changes: 1 addition & 1 deletion can/interfaces/pcan/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
""" """
"""PCAN CAN interface and driver bindings."""

__all__ = [
"PcanBus",
Expand Down
2 changes: 1 addition & 1 deletion can/interfaces/pcan/pcan.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@
import select

HAS_EVENTS = True
except Exception:
except ImportError:
pass


Expand Down
2 changes: 1 addition & 1 deletion can/interfaces/robotell.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion can/interfaces/socketcan/socketcan.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
Loading
Loading