Skip to content

Commit ddcefe2

Browse files
author
Felix Nieuwenhuizen
committed
Merge remote-tracking branch 'upstream/develop' into etas
2 parents e3928de + cee2d78 commit ddcefe2

File tree

3 files changed

+43
-61
lines changed

3 files changed

+43
-61
lines changed

can/interfaces/nixnet.py

Lines changed: 19 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,9 @@
1313
import time
1414
import struct
1515

16-
from can import CanError, BusABC, Message
16+
from can import BusABC, Message
17+
from ..exceptions import CanInitializationError, CanOperationError
18+
1719

1820
logger = logging.getLogger(__name__)
1921

@@ -28,18 +30,15 @@
2830
database,
2931
XnetError,
3032
)
31-
except ImportError:
32-
logger.error("Error, NIXNET python module cannot be loaded.")
33-
raise
33+
except ImportError as error:
34+
raise ImportError("NIXNET python module cannot be loaded") from error
3435
else:
35-
logger.error("NI-XNET interface is only available on Windows systems")
36-
raise NotImplementedError("NiXNET is not supported on not Win32 platforms")
36+
raise NotImplementedError("NiXNET only supported on Win32 platforms")
3737

3838

3939
class NiXNETcanBus(BusABC):
4040
"""
4141
The CAN Bus implemented for the NI-XNET interface.
42-
4342
"""
4443

4544
def __init__(
@@ -52,7 +51,7 @@ def __init__(
5251
brs=False,
5352
can_termination=False,
5453
log_errors=True,
55-
**kwargs
54+
**kwargs,
5655
):
5756
"""
5857
:param str channel:
@@ -69,9 +68,8 @@ def __init__(
6968
``is_error_frame`` set to True and ``arbitration_id`` will identify
7069
the error (default True)
7170
72-
:raises can.interfaces.nixnet.NiXNETError:
71+
:raises can.exceptions.CanInitializationError:
7372
If starting communication fails
74-
7573
"""
7674
self._rx_queue = []
7775
self.channel = channel
@@ -120,16 +118,18 @@ def __init__(
120118
self.__session_send.start()
121119
self.__session_receive.start()
122120

123-
except errors.XnetError as err:
124-
raise NiXNETError(function="__init__", error_message=err.args[0]) from None
121+
except errors.XnetError as error:
122+
raise CanInitializationError(
123+
f"{error.args[0]} ({error.error_type})", error.error_code
124+
) from None
125125

126126
self._is_filtered = False
127127
super(NiXNETcanBus, self).__init__(
128128
channel=channel,
129129
can_filters=can_filters,
130130
bitrate=bitrate,
131131
log_errors=log_errors,
132-
**kwargs
132+
**kwargs,
133133
)
134134

135135
def _recv_internal(self, timeout):
@@ -160,8 +160,7 @@ def _recv_internal(self, timeout):
160160
)
161161

162162
return msg, self._filters is None
163-
except Exception as e:
164-
# print('Error: ', e)
163+
except Exception:
165164
return None, self._filters is None
166165

167166
def send(self, msg, timeout=None):
@@ -174,7 +173,7 @@ def send(self, msg, timeout=None):
174173
:param float timeout:
175174
Max time to wait for the device to be ready in seconds, None if time is infinite
176175
177-
:raises can.interfaces.nixnet.NiXNETError:
176+
:raises can.exceptions.CanOperationError:
178177
If writing to transmit buffer fails.
179178
It does not wait for message to be ACKed currently.
180179
"""
@@ -201,8 +200,10 @@ def send(self, msg, timeout=None):
201200

202201
try:
203202
self.__session_send.frames.write([can_frame], timeout)
204-
except errors.XnetError as err:
205-
raise NiXNETError(function="send", error_message=err.args[0]) from None
203+
except errors.XnetError as error:
204+
raise CanOperationError(
205+
f"{error.args[0]} ({error.error_type})", error.error_code
206+
) from None
206207

207208
def reset(self):
208209
"""
@@ -254,18 +255,3 @@ def _detect_available_configs():
254255
logger.debug("An error occured while searching for configs: %s", str(error))
255256

256257
return configs
257-
258-
259-
# To-Do review error management, I don't like this implementation
260-
class NiXNETError(CanError):
261-
"""Error from NI-XNET driver."""
262-
263-
def __init__(self, function="", error_message=""):
264-
super(NiXNETError, self).__init__()
265-
#: Function that failed
266-
self.function = function
267-
#: Arguments passed to function
268-
self.error_message = error_message
269-
270-
def __str__(self):
271-
return "Function %s failed:\n%s" % (self.function, self.error_message)

can/interfaces/pcan/basic.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -814,7 +814,7 @@ def Read(self, Channel):
814814
"""Reads a CAN message from the receive queue of a PCAN Channel
815815
816816
Remarks:
817-
The return value of this method is a 3-touple, where
817+
The return value of this method is a 3-tuple, where
818818
the first value is the result (TPCANStatus) of the method.
819819
The order of the values are:
820820
[0]: A TPCANStatus error code
@@ -843,7 +843,7 @@ def ReadFD(self, Channel):
843843
"""Reads a CAN message from the receive queue of a FD capable PCAN Channel
844844
845845
Remarks:
846-
The return value of this method is a 3-touple, where
846+
The return value of this method is a 3-tuple, where
847847
the first value is the result (TPCANStatus) of the method.
848848
The order of the values are:
849849
[0]: A TPCANStatus error code
@@ -943,7 +943,7 @@ def GetValue(self, Channel, Parameter):
943943
of Hardware (PCAN Channel) being used. If a parameter is not available,
944944
a PCAN_ERROR_ILLPARAMTYPE error will be returned.
945945
946-
The return value of this method is a 2-touple, where
946+
The return value of this method is a 2-tuple, where
947947
the first value is the result (TPCANStatus) of the method and
948948
the second one, the asked value
949949
@@ -1038,7 +1038,7 @@ def GetErrorText(self, Error, Language=0):
10381038
Neutral (0x00), German (0x07), English (0x09), Spanish (0x0A),
10391039
Italian (0x10) and French (0x0C)
10401040
1041-
The return value of this method is a 2-touple, where
1041+
The return value of this method is a 2-tuple, where
10421042
the first value is the result (TPCANStatus) of the method and
10431043
the second one, the error text
10441044
@@ -1063,7 +1063,7 @@ def LookUpChannel(self, Parameters):
10631063
10641064
Remarks:
10651065
1066-
The return value of this method is a 2-touple, where
1066+
The return value of this method is a 2-tuple, where
10671067
the first value is the result (TPCANStatus) of the method and
10681068
the second one a TPCANHandle value
10691069

can/interfaces/robotell.py

Lines changed: 19 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import logging
77

88
from can import BusABC, Message
9+
from ..exceptions import CanInterfaceNotImplementedError
910

1011
logger = logging.getLogger(__name__)
1112

@@ -56,15 +57,17 @@ def __init__(
5657
):
5758
"""
5859
:param str channel:
59-
port of underlying serial or usb device (e.g. /dev/ttyUSB0, COM8, ...)
60-
Must not be empty.
60+
port of underlying serial or usb device (e.g. ``/dev/ttyUSB0``, ``COM8``, ...)
61+
Must not be empty. Can also end with ``@115200`` (or similarly) to specify the baudrate.
6162
:param int ttyBaudrate:
62-
baudrate of underlying serial or usb device
63+
baudrate of underlying serial or usb device (Ignored if set via the ``channel`` parameter)
6364
:param int bitrate:
6465
CAN Bitrate in bit/s. Value is stored in the adapter and will be used as default if no bitrate is specified
6566
:param bool rtscts:
6667
turn hardware handshake (RTS/CTS) on and off
6768
"""
69+
if serial is None:
70+
raise CanInterfaceNotImplementedError("The serial module is not installed")
6871

6972
if not channel: # if None or empty
7073
raise TypeError("Must specify a serial port.")
@@ -74,7 +77,7 @@ def __init__(
7477
channel, baudrate=ttyBaudrate, rtscts=rtscts
7578
)
7679

77-
## Disable flushing queued config ACKs on lookup channel (for unit tests)
80+
# Disable flushing queued config ACKs on lookup channel (for unit tests)
7881
self._loopback_test = channel == "loop://"
7982

8083
self._rxbuffer = bytearray() # raw bytes from the serial port
@@ -86,11 +89,10 @@ def __init__(
8689
if bitrate is not None:
8790
self.set_bitrate(bitrate)
8891

89-
self.channel_info = "Robotell USB-CAN s/n %s on %s" % (
90-
self.get_serial_number(1),
91-
channel,
92+
self.channel_info = (
93+
f"Robotell USB-CAN s/n {self.get_serial_number(1)} on {channel}"
9294
)
93-
logger.info("Using device: {}".format(self.channel_info))
95+
logger.info("Using device: %s", self.channel_info)
9496

9597
super().__init__(channel=channel, **kwargs)
9698

@@ -103,9 +105,7 @@ def set_bitrate(self, bitrate):
103105
if bitrate <= self._MAX_CAN_BAUD:
104106
self._writeconfig(self._CAN_BAUD_ID, bitrate)
105107
else:
106-
raise ValueError(
107-
"Invalid bitrate, must be less than " + str(self._MAX_CAN_BAUD)
108-
)
108+
raise ValueError(f"Invalid bitrate, must be less than {self._MAX_CAN_BAUD}")
109109

110110
def set_auto_retransmit(self, retrans_flag):
111111
"""
@@ -119,8 +119,8 @@ def set_auto_bus_management(self, auto_man):
119119
:param bool auto_man:
120120
Enable/disable automatic bus management
121121
"""
122-
## Not sure what "automatic bus managemenet" does. Does not seem to control
123-
## automatic ACK of CAN frames (listen only mode)
122+
# Not sure what "automatic bus management" does. Does not seem to control
123+
# automatic ACK of CAN frames (listen only mode)
124124
self._writeconfig(self._CAN_ABOM_ID, 1 if auto_man else 0)
125125

126126
def set_serial_rate(self, serial_bps):
@@ -161,7 +161,7 @@ def _getconfigsize(self, configid):
161161
return 4
162162
if configid == self._CAN_READ_SERIAL1 or configid <= self._CAN_READ_SERIAL2:
163163
return 8
164-
if configid >= self._CAN_FILTER_BASE_ID and configid <= self._CAN_FILTER_MAX_ID:
164+
if self._CAN_FILTER_BASE_ID <= configid <= self._CAN_FILTER_MAX_ID:
165165
return 8
166166
return 0
167167

@@ -178,9 +178,7 @@ def _readconfig(self, configid, timeout):
178178
newmsg = self._readmessage(not self._loopback_test, True, timeout)
179179
if newmsg is None:
180180
logger.warning(
181-
"Timeout waiting for response when reading config value {:04X}.".format(
182-
configid
183-
)
181+
f"Timeout waiting for response when reading config value {configid:04X}."
184182
)
185183
return None
186184
return newmsg[4:12]
@@ -211,8 +209,7 @@ def _writeconfig(self, configid, value, value2=0):
211209
newmsg = self._readmessage(not self._loopback_test, True, 1)
212210
if newmsg is None:
213211
logger.warning(
214-
"Timeout waiting for response when writing config value "
215-
+ str(configid)
212+
"Timeout waiting for response when writing config value %d", configid
216213
)
217214

218215
def _readmessage(self, flushold, cfgchannel, timeout):
@@ -261,17 +258,16 @@ def _readmessage(self, flushold, cfgchannel, timeout):
261258
cs = (cs + newmsg[idx]) & 0xFF
262259
if newmsg[16] == cs:
263260
# OK, valid message - place it in the correct queue
264-
if newmsg[13] == 0xFF: ## Check for config channel
261+
if newmsg[13] == 0xFF: # Check for config channel
265262
self._configmsg.append(newmsg)
266263
else:
267264
self._rxmsg.append(newmsg)
268265
else:
269266
logger.warning("Incorrect message checksum, discarded message")
270267
else:
271268
logger.warning(
272-
"Invalid message structure length "
273-
+ str(len(newmsg))
274-
+ ", ignoring message"
269+
"Invalid message structure length %d, ignoring message",
270+
len(newmsg),
275271
)
276272

277273
# Check if we have a message in the desired queue - if so copy and return

0 commit comments

Comments
 (0)