Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix formatter and bump ci tools #1167

Merged
merged 6 commits into from
Nov 11, 2021
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion can/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

log = logging.getLogger("can")

rc: Dict[str, Any] = dict()
rc: Dict[str, Any] = {}

from .listener import Listener, BufferedReader, RedirectReader, AsyncBufferedReader

Expand Down
2 changes: 1 addition & 1 deletion can/interfaces/canalystii.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def __init__(
elif isinstance(channel, int):
self.channels = [channel]
else: # Sequence[int]
self.channels = [c for c in channel]
self.channels = list(channel)

self.rx_queue = collections.deque(
maxlen=rx_queue_size
Expand Down
2 changes: 1 addition & 1 deletion can/interfaces/cantact.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def _detect_available_configs():

channels = []
for i in range(0, interface.channel_count()):
channels.append({"interface": "cantact", "channel": "ch:%d" % i})
channels.append({"interface": "cantact", "channel": f"ch:{i}"})
return channels

def __init__(
Expand Down
4 changes: 2 additions & 2 deletions can/interfaces/ics_neovi/neovi_bus.py
Original file line number Diff line number Diff line change
Expand Up @@ -226,8 +226,8 @@ def channel_to_netid(channel_name_or_id):
channel = getattr(ics, netid)
else:
raise ValueError(
"channel must be an integer or " "a valid ICS channel name"
)
"channel must be an integer or a valid ICS channel name"
) from None
return channel

@staticmethod
Expand Down
4 changes: 2 additions & 2 deletions can/interfaces/ixxat/canlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -604,12 +604,12 @@ def _inWaiting(self):
return 1

def flush_tx_buffer(self):
""" Flushes the transmit buffer on the IXXAT """
"""Flushes the transmit buffer on the IXXAT"""
# TODO #64: no timeout?
_canlib.canChannelWaitTxEvent(self._channel_handle, constants.INFINITE)

def _recv_internal(self, timeout):
""" Read a message from IXXAT device. """
"""Read a message from IXXAT device."""

# TODO: handling CAN error messages?
data_received = False
Expand Down
6 changes: 3 additions & 3 deletions can/interfaces/ixxat/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,15 @@


class VCITimeout(CanTimeoutError):
""" Wraps the VCI_E_TIMEOUT error """
"""Wraps the VCI_E_TIMEOUT error"""


class VCIError(CanOperationError):
""" Try to display errors that occur within the wrapped C library nicely. """
"""Try to display errors that occur within the wrapped C library nicely."""


class VCIRxQueueEmptyError(VCIError):
""" Wraps the VCI_E_RXQUEUE_EMPTY error """
"""Wraps the VCI_E_RXQUEUE_EMPTY error"""

def __init__(self):
super().__init__("Receive queue is empty")
Expand Down
6 changes: 1 addition & 5 deletions can/interfaces/kvaser/canlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -713,11 +713,7 @@ def get_channel_info(channel):
ctypes.sizeof(number),
)

return "%s, S/N %d (#%d)" % (
name.value.decode("ascii"),
serial.value,
number.value + 1,
)
return f"{name.value.decode('ascii')}, S/N {serial.value} (#{number.value + 1})"


init_kvaser_library()
6 changes: 3 additions & 3 deletions can/interfaces/neousys/neousys.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@


class NeousysCanSetup(Structure):
""" C CAN Setup struct """
"""C CAN Setup struct"""

_fields_ = [
("bitRate", c_uint),
Expand All @@ -58,7 +58,7 @@ class NeousysCanSetup(Structure):


class NeousysCanMsg(Structure):
""" C CAN Message struct """
"""C CAN Message struct"""

_fields_ = [
("id", c_uint),
Expand All @@ -75,7 +75,7 @@ class NeousysCanMsg(Structure):
# valid:1~4, Resynchronization Jump Width in time quanta
# valid:1~1023, CAN_CLK divider used to determine time quanta
class NeousysCanBitClk(Structure):
""" C CAN BIT Clock struct """
"""C CAN BIT Clock struct"""

_fields_ = [
("syncPropPhase1Seg", c_ushort),
Expand Down
2 changes: 1 addition & 1 deletion can/interfaces/nixnet.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
)
except ImportError:
logger.error("Error, NIXNET python module cannot be loaded.")
raise ImportError()
raise
else:
logger.error("NI-XNET interface is only available on Windows systems")
raise NotImplementedError("NiXNET is not supported on not Win32 platforms")
Expand Down
2 changes: 1 addition & 1 deletion can/interfaces/seeedstudio/seeedstudio.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ def __init__(
"could not create the serial device"
) from error

super(SeeedBus, self).__init__(channel=channel, *args, **kwargs)
super().__init__(channel=channel, *args, **kwargs)
self.init_frame()

def shutdown(self):
Expand Down
2 changes: 1 addition & 1 deletion can/interfaces/socketcan/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from typing import cast, Iterable, Optional

from can.interfaces.socketcan.constants import CAN_EFF_FLAG
import can.typechecking as typechecking
from can import typechecking

log = logging.getLogger(__name__)

Expand Down
2 changes: 1 addition & 1 deletion can/interfaces/systec/structures.py
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,7 @@ class HardwareInfoEx(Structure):
]

def __init__(self):
super(HardwareInfoEx, self).__init__(sizeof(HardwareInfoEx))
super().__init__(sizeof(HardwareInfoEx))

def __eq__(self, other):
if not isinstance(other, HardwareInfoEx):
Expand Down
9 changes: 5 additions & 4 deletions can/interfaces/udp_multicast/bus.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,13 +121,13 @@ def _recv_internal(self, timeout: Optional[float]):

return can_message, False

def send(self, message: can.Message, timeout: Optional[float] = None) -> None:
if not self.is_fd and message.is_fd:
def send(self, msg: can.Message, timeout: Optional[float] = None) -> None:
if not self.is_fd and msg.is_fd:
raise can.CanOperationError(
"cannot send FD message over bus with CAN FD disabled"
)

data = pack_message(message)
data = pack_message(msg)
self._multicast.send(data, timeout)

def fileno(self) -> int:
Expand Down Expand Up @@ -186,8 +186,9 @@ def __init__(
sock = self._create_socket(address_family)
except OSError as error:
log.info(
f"could not connect to the multicast IP network of candidate %s; reason: {error}",
"could not connect to the multicast IP network of candidate %s; reason: %s",
connection_candidates,
error,
)
if sock is not None:
self._socket = sock
Expand Down
23 changes: 11 additions & 12 deletions can/interfaces/vector/canlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,6 @@
)
from can.typechecking import AutoDetectedConfig, CanFilters

from .exceptions import VectorError

# Define Module Logger
# ====================
LOG = logging.getLogger(__name__)
Expand Down Expand Up @@ -140,7 +138,8 @@ def __init__(
"""
if os.name != "nt" and not kwargs.get("_testing", False):
raise CanInterfaceNotImplementedError(
f'The Vector interface is only supported on Windows, but you are running "{os.name}"'
f"The Vector interface is only supported on Windows, "
f'but you are running "{os.name}"'
)

if xldriver is None:
Expand All @@ -163,7 +162,7 @@ def __init__(
self._app_name = app_name.encode() if app_name is not None else b""
self.channel_info = "Application %s: %s" % (
app_name,
", ".join("CAN %d" % (ch + 1) for ch in self.channels),
", ".join(f"CAN {ch + 1}" for ch in self.channels),
)

if serial is not None:
Expand Down Expand Up @@ -358,8 +357,8 @@ def _apply_filters(self, filters) -> None:
if can_filter.get("extended")
else xldefine.XL_AcceptanceFilter.XL_CAN_STD,
)
except VectorOperationError as exc:
LOG.warning("Could not set filters: %s", exc)
except VectorOperationError as exception:
LOG.warning("Could not set filters: %s", exception)
# go to fallback
else:
self._is_filtered = True
Expand Down Expand Up @@ -400,8 +399,8 @@ def _recv_internal(
else:
msg = self._recv_can()

except VectorOperationError as exc:
if exc.error_code != xldefine.XL_Status.XL_ERR_QUEUE_IS_EMPTY:
except VectorOperationError as exception:
if exception.error_code != xldefine.XL_Status.XL_ERR_QUEUE_IS_EMPTY:
raise
else:
if msg:
Expand Down Expand Up @@ -435,7 +434,7 @@ def _recv_canfd(self) -> Optional[Message]:
data_struct = xl_can_rx_event.tagData.canTxOkMsg
else:
self.handle_canfd_event(xl_can_rx_event)
return
return None

msg_id = data_struct.canId
dlc = dlc2len(data_struct.dlc)
Expand Down Expand Up @@ -475,7 +474,7 @@ def _recv_can(self) -> Optional[Message]:

if xl_event.tag != xldefine.XL_EventTags.XL_RECEIVE_MSG:
self.handle_can_event(xl_event)
return
return None

msg_id = xl_event.tagData.msg.id
dlc = xl_event.tagData.msg.dlc
Expand Down Expand Up @@ -520,8 +519,8 @@ def handle_canfd_event(self, event: xlclass.XLcanRxEvent) -> None:
when `event.tag` is not `XL_CAN_EV_TAG_RX_OK` or `XL_CAN_EV_TAG_TX_OK`.
Subclasses can implement this method.

:param event: `XLcanRxEvent` that could have a `XL_CAN_EV_TAG_RX_ERROR`, `XL_CAN_EV_TAG_TX_ERROR`,
`XL_TIMER` or `XL_CAN_EV_TAG_CHIP_STATE` tag.
:param event: `XLcanRxEvent` that could have a `XL_CAN_EV_TAG_RX_ERROR`,
`XL_CAN_EV_TAG_TX_ERROR`, `XL_TIMER` or `XL_CAN_EV_TAG_CHIP_STATE` tag.
"""

def send(self, msg: Message, timeout: Optional[float] = None):
Expand Down
2 changes: 1 addition & 1 deletion can/interfaces/virtual.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ def __init__(

# the channel identifier may be an arbitrary object
self.channel_id = channel
self.channel_info = "Virtual bus channel {}".format(self.channel_id)
self.channel_info = f"Virtual bus channel {self.channel_id}"
self.receive_own_messages = receive_own_messages
self._open = True

Expand Down
30 changes: 16 additions & 14 deletions can/io/asc.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
- under `test/data/logfile.asc`
"""

from typing import cast, Any, Generator, IO, List, Optional, Union, Dict
from typing import cast, Any, Generator, IO, List, Optional, Dict

from datetime import datetime
import time
Expand Down Expand Up @@ -73,8 +73,10 @@ def _extract_header(self):
elif lower_case.startswith("base"):
try:
_, base, _, timestamp_format = line.split()
except ValueError:
raise Exception("Unsupported header string format: {}".format(line))
except ValueError as exception:
raise Exception(
f"Unsupported header string format: {line}"
) from exception
self.base = base
self._converted_base = self._check_base(self.base)
self.timestamps_format = timestamp_format
Expand Down Expand Up @@ -135,8 +137,8 @@ def _process_classic_can_frame(
# Error Frame
msg_kwargs["is_error_frame"] = True
else:
abr_id_str, dir, rest_of_message = line.split(None, 2)
msg_kwargs["is_rx"] = dir == "Rx"
abr_id_str, direction, rest_of_message = line.split(None, 2)
msg_kwargs["is_rx"] = direction == "Rx"
self._extract_can_id(abr_id_str, msg_kwargs)

if rest_of_message[0].lower() == "r":
Expand Down Expand Up @@ -164,10 +166,10 @@ def _process_classic_can_frame(
return Message(**msg_kwargs)

def _process_fd_can_frame(self, line: str, msg_kwargs: Dict[str, Any]) -> Message:
channel, dir, rest_of_message = line.split(None, 2)
channel, direction, rest_of_message = line.split(None, 2)
# See ASCWriter
msg_kwargs["channel"] = int(channel) - 1
msg_kwargs["is_rx"] = dir == "Rx"
msg_kwargs["is_rx"] = direction == "Rx"

# CAN FD error frame
if rest_of_message.strip()[:10].lower() == "errorframe":
Expand Down Expand Up @@ -291,7 +293,7 @@ def __init__(

# write start of file header
now = datetime.now().strftime(self.FORMAT_START_OF_FILE_DATE)
self.file.write("date %s\n" % now)
self.file.write(f"date {now}\n")
self.file.write("base hex timestamps absolute\n")
self.file.write("internal events logged\n")

Expand Down Expand Up @@ -327,7 +329,7 @@ def log_event(self, message: str, timestamp: Optional[float] = None) -> None:
formatted_date = time.strftime(
self.FORMAT_DATE.format(mlsec), time.localtime(self.last_timestamp)
)
self.file.write("Begin Triggerblock %s\n" % formatted_date)
self.file.write(f"Begin Triggerblock {formatted_date}\n")
self.header_written = True
self.log_event("Start of measurement") # caution: this is a recursive call!
# Use last known timestamp if unknown
Expand All @@ -342,15 +344,15 @@ def log_event(self, message: str, timestamp: Optional[float] = None) -> None:
def on_message_received(self, msg: Message) -> None:

if msg.is_error_frame:
self.log_event("{} ErrorFrame".format(self.channel), msg.timestamp)
self.log_event(f"{self.channel} ErrorFrame", msg.timestamp)
return
if msg.is_remote_frame:
dtype = "r {:x}".format(msg.dlc) # New after v8.5
dtype = f"r {msg.dlc:x}" # New after v8.5
data: List[str] = []
else:
dtype = "d {:x}".format(msg.dlc)
data = ["{:02X}".format(byte) for byte in msg.data]
arb_id = "{:X}".format(msg.arbitration_id)
dtype = f"d {msg.dlc:x}"
data = [f"{byte:02X}" for byte in msg.data]
arb_id = f"{msg.arbitration_id:X}"
if msg.is_extended_id:
arb_id += "x"
channel = channel2int(msg.channel)
Expand Down
4 changes: 2 additions & 2 deletions can/io/blf.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ def _parse_data(self, data):
if pos + 8 > max_pos:
# Not enough data in container
return
raise BLFParseError("Could not find next object")
raise BLFParseError("Could not find next object") from None
header = unpack_obj_header_base(data, pos)
# print(header)
signature, _, header_version, obj_size, obj_type = header
Expand Down Expand Up @@ -258,7 +258,7 @@ def _parse_data(self, data):
factor = 1e-5 if flags == 1 else 1e-9
timestamp = timestamp * factor + start_timestamp

if obj_type == CAN_MESSAGE or obj_type == CAN_MESSAGE2:
if obj_type in (CAN_MESSAGE, CAN_MESSAGE2):
channel, flags, dlc, can_id, can_data = unpack_can_msg(data, pos)
yield Message(
timestamp=timestamp,
Expand Down
1 change: 1 addition & 0 deletions can/io/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ def __init__(
# file is None or some file-like object
self.file = cast(Optional[can.typechecking.FileLike], file)
else:
# pylint: disable=consider-using-with
# file is some path-like object
self.file = open(cast(can.typechecking.StringPathLike, file), mode)

Expand Down