Skip to content

Commit fcbef0e

Browse files
authored
Specific Exceptions: Adapting udp_multicast interface (hardbyte#1089)
* Adjust exceptions in udp_multicast interface * Format code with black
1 parent 689a87d commit fcbef0e

File tree

2 files changed

+34
-11
lines changed

2 files changed

+34
-11
lines changed

can/interfaces/udp_multicast/bus.py

Lines changed: 31 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,9 @@ def __init__(
9292
check_msgpack_installed()
9393

9494
if receive_own_messages:
95-
raise NotImplementedError("receiving own messages is not yet implemented")
95+
raise can.CanInterfaceNotImplementedError(
96+
"receiving own messages is not yet implemented"
97+
)
9698

9799
super().__init__(channel, **kwargs)
98100

@@ -105,7 +107,14 @@ def _recv_internal(self, timeout: Optional[float]):
105107
return None, False
106108

107109
data, _, timestamp = result
108-
can_message = unpack_message(data, replace={"timestamp": timestamp})
110+
try:
111+
can_message = unpack_message(
112+
data, replace={"timestamp": timestamp}, check=True
113+
)
114+
except Exception as exception:
115+
raise can.CanOperationError(
116+
"could not unpack received message"
117+
) from exception
109118

110119
if not self.is_fd and can_message.is_fd:
111120
return None, False
@@ -114,7 +123,9 @@ def _recv_internal(self, timeout: Optional[float]):
114123

115124
def send(self, message: can.Message, timeout: Optional[float] = None) -> None:
116125
if not self.is_fd and message.is_fd:
117-
raise RuntimeError("cannot send FD message over bus with CAN FD disabled")
126+
raise can.CanOperationError(
127+
"cannot send FD message over bus with CAN FD disabled"
128+
)
118129

119130
data = pack_message(message)
120131
self._multicast.send(data, timeout)
@@ -149,7 +160,10 @@ def _detect_available_configs() -> List[AutoDetectedConfig]:
149160

150161

151162
class GeneralPurposeUdpMulticastBus:
152-
"""A general purpose send and receive handler for multicast over IP/UDP."""
163+
"""A general purpose send and receive handler for multicast over IP/UDP.
164+
165+
However, it raises CAN-specific exceptions for convenience.
166+
"""
153167

154168
def __init__(
155169
self, group: str, port: int, hop_limit: int, max_buffer: int = 4096
@@ -178,7 +192,9 @@ def __init__(
178192
if sock is not None:
179193
self._socket = sock
180194
else:
181-
raise RuntimeError("could not connect to a multicast IP network")
195+
raise can.CanInitializationError(
196+
"could not connect to a multicast IP network"
197+
)
182198

183199
# used in recv()
184200
self.received_timestamp_struct = "@ll"
@@ -193,8 +209,10 @@ def _create_socket(self, address_family: socket.AddressFamily) -> socket.socket:
193209
"""Creates a new socket. This might fail and raise an exception!
194210
195211
:param address_family: whether this is of type `socket.AF_INET` or `socket.AF_INET6`
196-
:raises OSError: if the socket could not be opened or configured correctly; in this case, it is
197-
guaranteed to be closed/cleaned up
212+
213+
:raises can.CanInitializationError:
214+
if the socket could not be opened or configured correctly; in this case, it is
215+
guaranteed to be closed/cleaned up
198216
"""
199217
# create the UDP socket
200218
# this might already fail but then there is nothing to clean up
@@ -243,7 +261,9 @@ def _create_socket(self, address_family: socket.AddressFamily) -> socket.socket:
243261
log.warning("Could not close partly configured socket: %s", close_error)
244262

245263
# still raise the error
246-
raise error
264+
raise can.CanInitializationError(
265+
"could not create or configure socket"
266+
) from error
247267

248268
def send(self, data: bytes, timeout: Optional[float] = None) -> None:
249269
"""Send data to all group members. This call blocks.
@@ -283,7 +303,9 @@ def recv(
283303
ready_receive_sockets, _, _ = select.select([self._socket], [], [], timeout)
284304
except socket.error as exc:
285305
# something bad (not a timeout) happened (e.g. the interface went down)
286-
raise can.CanError(f"Failed to wait for IP/UDP socket: {exc}")
306+
raise can.CanOperationError(
307+
f"Failed to wait for IP/UDP socket: {exc}"
308+
) from exc
287309

288310
if ready_receive_sockets: # not empty
289311
# fetch data & source address

can/interfaces/udp_multicast/utils.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
from typing import Optional
88

99
from can import Message
10+
from can import CanInterfaceNotImplementedError
1011
from can.typechecking import ReadableBytesLike
1112

1213
try:
@@ -16,9 +17,9 @@
1617

1718

1819
def check_msgpack_installed() -> None:
19-
"""Raises a `RuntimeError` if `msgpack` is not installed."""
20+
"""Raises a :class:`can.CanInterfaceNotImplementedError` if `msgpack` is not installed."""
2021
if msgpack is None:
21-
raise RuntimeError("msgpack not installed")
22+
raise CanInterfaceNotImplementedError("msgpack not installed")
2223

2324

2425
def pack_message(message: Message) -> bytes:

0 commit comments

Comments
 (0)