-
Notifications
You must be signed in to change notification settings - Fork 674
Expand file tree
/
Copy pathseeedstudio.py
More file actions
341 lines (280 loc) · 10.9 KB
/
seeedstudio.py
File metadata and controls
341 lines (280 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
"""
To Support the Seeed USB-Can analyzer interface. The device will appear
as a serial port, for example "/dev/ttyUSB0" on Linux machines
or "COM1" on Windows.
https://www.seeedstudio.com/USB-CAN-Analyzer-p-2888.html
SKU 114991193
"""
import io
import logging
import struct
from time import time
import can
from can import BusABC, CanProtocol, Message
logger = logging.getLogger("seeedbus")
try:
import serial
except ImportError:
logger.warning(
"You won't be able to use the serial can backend without "
"the serial module installed!"
)
serial = None
class SeeedBus(BusABC):
"""
Enable basic can communication over a USB-CAN-Analyzer device.
"""
BITRATE = {
1000000: 0x01,
800000: 0x02,
500000: 0x03,
400000: 0x04,
250000: 0x05,
200000: 0x06,
125000: 0x07,
100000: 0x08,
50000: 0x09,
20000: 0x0A,
10000: 0x0B,
5000: 0x0C,
}
FRAMETYPE = {"STD": 0x01, "EXT": 0x02}
OPERATIONMODE = {
"normal": 0x00,
"loopback": 0x01,
"silent": 0x02,
"loopback_and_silent": 0x03,
}
def __init__(
self,
channel,
baudrate=2000000,
timeout=0.1,
frame_type="STD",
operation_mode="normal",
bitrate=500000,
can_filters=None,
**kwargs,
):
"""
:param str channel:
The serial device to open. For example "/dev/ttyS1" or
"/dev/ttyUSB0" on Linux or "COM1" on Windows systems.
:param baudrate:
The default matches required baudrate
:param float timeout:
Timeout for the serial device in seconds (default 0.1).
:param str frame_type:
STD or EXT, to select standard or extended messages
:param operation_mode
normal, loopback, silent or loopback_and_silent.
:param bitrate
CAN bus bit rate, selected from available list.
:param can_filters:
A list of CAN filter dictionaries. If one filter is provided,
it will be used by the high-performance hardware filter. If
zero or more than one filter is provided, software-based
filtering will be used. Defaults to None (no filtering).
:raises can.CanInitializationError: If the given parameters are invalid.
:raises can.CanInterfaceNotImplementedError: If the serial module is not installed.
"""
if serial is None:
raise can.CanInterfaceNotImplementedError(
"the serial module is not installed"
)
can_id = 0x00
can_mask = 0x00
self._is_filtered = False
if can_filters and len(can_filters) == 1:
self._is_filtered = True
hw_filter = can_filters[0]
can_id = hw_filter["can_id"]
can_mask = hw_filter["can_mask"]
self.bit_rate = bitrate
self.frame_type = frame_type
self.op_mode = operation_mode
self.filter_id = struct.pack("<I", can_id)
self.mask_id = struct.pack("<I", can_mask)
self._can_protocol = CanProtocol.CAN_20
if not channel:
raise can.CanInitializationError("Must specify a serial port.")
self.channel_info = "Serial interface: " + channel
try:
self.ser = serial.Serial(
channel, baudrate=baudrate, timeout=timeout, rtscts=False
)
except ValueError as error:
raise can.CanInitializationError(
"could not create the serial device"
) from error
super().__init__(channel=channel, can_filters=can_filters, **kwargs)
self.init_frame()
def shutdown(self):
"""
Close the serial interface.
"""
super().shutdown()
self.ser.close()
def init_frame(self):
"""
Send init message to setup the device for comms. this is called during
interface creation.
"""
byte_msg = bytearray()
byte_msg.append(0xAA) # Frame Start Byte 1
byte_msg.append(0x55) # Frame Start Byte 2
byte_msg.append(0x12) # Initialization Message ID
byte_msg.append(SeeedBus.BITRATE[self.bit_rate]) # CAN Baud Rate
byte_msg.append(SeeedBus.FRAMETYPE[self.frame_type])
byte_msg.extend(self.filter_id)
byte_msg.extend(self.mask_id)
byte_msg.append(SeeedBus.OPERATIONMODE[self.op_mode])
byte_msg.append(0x01) # Follows 'Send once' in windows app.
byte_msg.extend([0x00] * 4) # Manual bitrate config, details unknown.
crc = sum(byte_msg[2:]) & 0xFF
byte_msg.append(crc)
logger.debug("init_frm:\t%s", byte_msg.hex())
try:
self.ser.write(byte_msg)
except Exception as error:
raise can.CanInitializationError("could send init frame") from error
def flush_buffer(self):
self.ser.flushInput()
def status_frame(self):
"""
Send status request message over the serial device. The device will
respond but details of error codes are unknown but are logged - DEBUG.
"""
byte_msg = bytearray()
byte_msg.append(0xAA) # Frame Start Byte 1
byte_msg.append(0x55) # Frame Start Byte 2
byte_msg.append(0x04) # Status Message ID
byte_msg.append(0x00) # In response packet - Rx error count
byte_msg.append(0x00) # In response packet - Tx error count
byte_msg.extend([0x00] * 14)
crc = sum(byte_msg[2:]) & 0xFF
byte_msg.append(crc)
logger.debug("status_frm:\t%s", byte_msg.hex())
self._write(byte_msg)
def send(self, msg, timeout=None):
"""
Send a message over the serial device.
:param can.Message msg:
Message to send.
:param timeout:
This parameter will be ignored. The timeout value of the channel is
used instead.
"""
byte_msg = bytearray()
byte_msg.append(0xAA)
m_type = 0xC0
if msg.is_extended_id:
m_type += 1 << 5
if msg.is_remote_frame:
m_type += 1 << 4
m_type += msg.dlc
byte_msg.append(m_type)
if msg.is_extended_id:
a_id = struct.pack("<I", msg.arbitration_id)
else:
a_id = struct.pack("<H", msg.arbitration_id)
byte_msg.extend(a_id)
byte_msg.extend(msg.data)
byte_msg.append(0x55)
logger.debug("sending:\t%s", byte_msg.hex())
self._write(byte_msg)
def _write(self, byte_msg: bytearray) -> None:
try:
self.ser.write(byte_msg)
except serial.PortNotOpenError as error:
raise can.CanOperationError("writing to closed port") from error
except serial.SerialTimeoutException as error:
raise can.CanTimeoutError() from error
def _recv_internal(self, timeout):
"""
Read a message from the serial device.
:param timeout:
.. warning::
This parameter will be ignored. The timeout value of the
channel is used.
:return:
1. a message that was read or None on timeout
2. a bool that is True if hw_filter is enabled, else False
:rtype:
can.Message, bool
"""
try:
# ser.read can return an empty string
# or raise a SerialException
rx_byte_1 = self.ser.read()
except serial.PortNotOpenError as error:
raise can.CanOperationError("reading from closed port") from error
except serial.SerialException:
return None, self._is_filtered
if rx_byte_1 and ord(rx_byte_1) == 0xAA:
try:
if self.ser.in_waiting >= 1:
rx_byte_2_opt = self.ser.read()
else:
# Should not get to this line
logger.debug("received 0xAA, then serial stopped")
rx_byte_2_opt = 0x00
rx_byte_2 = ord(rx_byte_2_opt)
time_stamp = time()
if rx_byte_2 == 0x55:
status = bytearray([0xAA, 0x55])
status += bytearray(self.ser.read(18))
logger.debug("status resp:\t%s", status.hex())
else:
length = int(rx_byte_2 & 0x0F)
is_extended = bool(rx_byte_2 & 0x20)
is_remote = bool(rx_byte_2 & 0x10)
if is_extended:
s_3_4_5_6 = bytearray(self.ser.read(4))
arb_id = (struct.unpack("<I", s_3_4_5_6))[0]
else:
s_3_4 = bytearray(self.ser.read(2))
arb_id = (struct.unpack("<H", s_3_4))[0]
data = bytearray(self.ser.read(length))
if self.ser.in_waiting >= 1:
end_packet_opt = self.ser.read()
else:
logger.debug("no end byte?")
# Seems to be a bug in the seeedstudio-dongle, rarely
# the end-byte is missing. Rarely: ~0.1% of the packets?
# The communication works otherwise fine, no bad data
# packets have been observed. Probably the underlying
# usb-driver serves as a good protection.
# No bad packets (corrupted data), despite this one
# end-byte has been observed.
# To ensure no data is lost, we fake an end-byte here.
end_packet_opt = "U"
end_packet = ord(end_packet_opt)
if end_packet == 0x55:
msg = Message(
timestamp=time_stamp,
arbitration_id=arb_id,
is_extended_id=is_extended,
is_remote_frame=is_remote,
dlc=length,
data=data,
)
logger.debug("recv message: %s", str(msg))
return msg, self._is_filtered
else:
return None, self._is_filtered
except serial.PortNotOpenError as error:
raise can.CanOperationError("reading from closed port") from error
except serial.SerialException as error:
raise can.CanOperationError(
"failed to read message information"
) from error
return None, self._is_filtered
def fileno(self):
try:
return self.ser.fileno()
except io.UnsupportedOperation as excption:
logger.warning(
"fileno is not implemented using current CAN bus: %s", str(excption)
)
return -1