10
10
import struct
11
11
import io
12
12
from time import time
13
+
14
+ import can
13
15
from can import BusABC , Message
14
16
15
17
logger = logging .getLogger ("seeedbus" )
@@ -84,19 +86,32 @@ def __init__(
84
86
:param bitrate
85
87
CAN bus bit rate, selected from available list.
86
88
89
+ :raises can.CanInitializationError: If the given parameters are invalid.
90
+ :raises can.CanInterfaceNotImplementedError: If the serial module is not installed.
87
91
"""
92
+
93
+ if serial is None :
94
+ raise can .CanInterfaceNotImplementedError (
95
+ "the serial module is not installed"
96
+ )
97
+
88
98
self .bit_rate = bitrate
89
99
self .frame_type = frame_type
90
100
self .op_mode = operation_mode
91
101
self .filter_id = bytearray ([0x00 , 0x00 , 0x00 , 0x00 ])
92
102
self .mask_id = bytearray ([0x00 , 0x00 , 0x00 , 0x00 ])
93
103
if not channel :
94
- raise ValueError ("Must specify a serial port." )
104
+ raise can . CanInitializationError ("Must specify a serial port." )
95
105
96
106
self .channel_info = "Serial interface: " + channel
97
- self .ser = serial .Serial (
98
- channel , baudrate = baudrate , timeout = timeout , rtscts = False
99
- )
107
+ try :
108
+ self .ser = serial .Serial (
109
+ channel , baudrate = baudrate , timeout = timeout , rtscts = False
110
+ )
111
+ except ValueError as error :
112
+ raise can .CanInitializationError (
113
+ "could not create the serial device"
114
+ ) from error
100
115
101
116
super (SeeedBus , self ).__init__ (channel = channel , * args , ** kwargs )
102
117
self .init_frame ()
@@ -133,7 +148,10 @@ def init_frame(self, timeout=None):
133
148
byte_msg .append (crc )
134
149
135
150
logger .debug ("init_frm:\t %s" , byte_msg .hex ())
136
- self .ser .write (byte_msg )
151
+ try :
152
+ self .ser .write (byte_msg )
153
+ except Exception as error :
154
+ raise can .CanInitializationError ("could send init frame" ) from error
137
155
138
156
def flush_buffer (self ):
139
157
self .ser .flushInput ()
@@ -160,7 +178,7 @@ def status_frame(self, timeout=None):
160
178
byte_msg .append (crc )
161
179
162
180
logger .debug ("status_frm:\t %s" , byte_msg .hex ())
163
- self .ser . write (byte_msg )
181
+ self ._write (byte_msg )
164
182
165
183
def send (self , msg , timeout = None ):
166
184
"""
@@ -197,7 +215,15 @@ def send(self, msg, timeout=None):
197
215
byte_msg .append (0x55 )
198
216
199
217
logger .debug ("sending:\t %s" , byte_msg .hex ())
200
- self .ser .write (byte_msg )
218
+ self ._write (byte_msg )
219
+
220
+ def _write (self , byte_msg : bytearray ) -> None :
221
+ try :
222
+ self .ser .write (byte_msg )
223
+ except serial .PortNotOpenError as error :
224
+ raise can .CanOperationError ("writing to closed port" ) from error
225
+ except serial .SerialTimeoutException as error :
226
+ raise can .CanTimeoutError () from error
201
227
202
228
def _recv_internal (self , timeout ):
203
229
"""
@@ -220,50 +246,64 @@ def _recv_internal(self, timeout):
220
246
# or raise a SerialException
221
247
rx_byte_1 = self .ser .read ()
222
248
249
+ except serial .PortNotOpenError as error :
250
+ raise can .CanOperationError ("reading from closed port" ) from error
223
251
except serial .SerialException :
224
252
return None , False
225
253
226
254
if rx_byte_1 and ord (rx_byte_1 ) == 0xAA :
227
- rx_byte_2 = ord (self .ser .read ())
228
- time_stamp = time ()
229
- if rx_byte_2 == 0x55 :
230
- status = bytearray ([0xAA , 0x55 ])
231
- status += bytearray (self .ser .read (18 ))
232
- logger .debug ("status resp:\t %s" , status .hex ())
233
-
234
- else :
235
- length = int (rx_byte_2 & 0x0F )
236
- is_extended = bool (rx_byte_2 & 0x20 )
237
- is_remote = bool (rx_byte_2 & 0x10 )
238
- if is_extended :
239
- s_3_4_5_6 = bytearray (self .ser .read (4 ))
240
- arb_id = (struct .unpack ("<I" , s_3_4_5_6 ))[0 ]
255
+ try :
256
+ rx_byte_2 = ord (self .ser .read ())
241
257
242
- else :
243
- s_3_4 = bytearray (self .ser .read (2 ))
244
- arb_id = (struct .unpack ("<H" , s_3_4 ))[0 ]
245
-
246
- data = bytearray (self .ser .read (length ))
247
- end_packet = ord (self .ser .read ())
248
- if end_packet == 0x55 :
249
- msg = Message (
250
- timestamp = time_stamp ,
251
- arbitration_id = arb_id ,
252
- is_extended_id = is_extended ,
253
- is_remote_frame = is_remote ,
254
- dlc = length ,
255
- data = data ,
256
- )
257
- logger .debug ("recv message: %s" , str (msg ))
258
- return msg , False
258
+ time_stamp = time ()
259
+ if rx_byte_2 == 0x55 :
260
+ status = bytearray ([0xAA , 0x55 ])
261
+ status += bytearray (self .ser .read (18 ))
262
+ logger .debug ("status resp:\t %s" , status .hex ())
259
263
260
264
else :
261
- return None , False
265
+ length = int (rx_byte_2 & 0x0F )
266
+ is_extended = bool (rx_byte_2 & 0x20 )
267
+ is_remote = bool (rx_byte_2 & 0x10 )
268
+ if is_extended :
269
+ s_3_4_5_6 = bytearray (self .ser .read (4 ))
270
+ arb_id = (struct .unpack ("<I" , s_3_4_5_6 ))[0 ]
271
+
272
+ else :
273
+ s_3_4 = bytearray (self .ser .read (2 ))
274
+ arb_id = (struct .unpack ("<H" , s_3_4 ))[0 ]
275
+
276
+ data = bytearray (self .ser .read (length ))
277
+ end_packet = ord (self .ser .read ())
278
+ if end_packet == 0x55 :
279
+ msg = Message (
280
+ timestamp = time_stamp ,
281
+ arbitration_id = arb_id ,
282
+ is_extended_id = is_extended ,
283
+ is_remote_frame = is_remote ,
284
+ dlc = length ,
285
+ data = data ,
286
+ )
287
+ logger .debug ("recv message: %s" , str (msg ))
288
+ return msg , False
289
+
290
+ else :
291
+ return None , False
292
+
293
+ except serial .PortNotOpenError as error :
294
+ raise can .CanOperationError ("reading from closed port" ) from error
295
+ except serial .SerialException as error :
296
+ raise can .CanOperationError (
297
+ "failed to read message information"
298
+ ) from error
262
299
263
300
return None , None
264
301
265
302
def fileno (self ):
266
303
try :
267
304
return self .ser .fileno ()
268
- except io .UnsupportedOperation :
269
- raise NotImplementedError ("fileno is not implemented using current CAN bus" )
305
+ except io .UnsupportedOperation as excption :
306
+ logger .warning (
307
+ "fileno is not implemented using current CAN bus: %s" , str (excption )
308
+ )
309
+ return - 1
0 commit comments