@@ -47,6 +47,9 @@ class slcanBus(BusABC):
4747
4848 _SLEEP_AFTER_SERIAL_OPEN = 2 # in seconds
4949
50+ _OK = b"\r "
51+ _ERROR = b"\a "
52+
5053 LINE_TERMINATOR = b"\r "
5154
5255 def __init__ (
@@ -81,10 +84,8 @@ def __init__(
8184
8285 if not channel : # if None or empty
8386 raise TypeError ("Must specify a serial port." )
84-
8587 if "@" in channel :
8688 (channel , ttyBaudrate ) = channel .split ("@" )
87-
8889 self .serialPortOrig = serial .serial_for_url (
8990 channel , baudrate = ttyBaudrate , rtscts = rtscts
9091 )
@@ -95,90 +96,123 @@ def __init__(
9596
9697 if bitrate is not None and btr is not None :
9798 raise ValueError ("Bitrate and btr mutually exclusive." )
98-
9999 if bitrate is not None :
100- self .close ()
101- if bitrate in self ._BITRATES :
102- self .write (self ._BITRATES [bitrate ])
103- else :
104- raise ValueError (
105- "Invalid bitrate, choose one of "
106- + (", " .join (self ._BITRATES ))
107- + "."
108- )
109-
100+ self .set_bitrate (self , bitrate )
110101 if btr is not None :
111- self .close ()
112- self .write ("s" + btr )
113-
102+ self .set_bitrate_reg (self , btr )
114103 self .open ()
115104
116105 super ().__init__ (
117106 channel , ttyBaudrate = 115200 , bitrate = None , rtscts = False , ** kwargs
118107 )
119108
120- def write (self , string ):
109+ def set_bitrate (self , bitrate ):
110+ """
111+ :raise ValueError: if both *bitrate* is not among the possible values
112+
113+ :param int bitrate:
114+ Bitrate in bit/s
115+ """
116+ self .close ()
117+ if bitrate in self ._BITRATES :
118+ self ._write (self ._BITRATES [bitrate ])
119+ else :
120+ raise ValueError (
121+ "Invalid bitrate, choose one of " + (", " .join (self ._BITRATES )) + "."
122+ )
123+ self .open ()
124+
125+ def set_bitrate_reg (self , btr ):
126+ """
127+ :param str btr:
128+ BTR register value to set custom can speed
129+ """
130+ self .close ()
131+ self ._write ("s" + btr )
132+ self .open ()
133+
134+ def _write (self , string ):
121135 self .serialPortOrig .write (string .encode () + self .LINE_TERMINATOR )
122136 self .serialPortOrig .flush ()
123137
138+ def _read (self , timeout ):
139+
140+ # first read what is already in receive buffer
141+ while self .serialPortOrig .in_waiting :
142+ self ._buffer += self .serialPortOrig .read ()
143+ # if we still don't have a complete message, do a blocking read
144+ start = time .time ()
145+ time_left = timeout
146+ while not (ord (self ._OK ) in self ._buffer or ord (self ._ERROR ) in self ._buffer ):
147+ self .serialPortOrig .timeout = time_left
148+ byte = self .serialPortOrig .read ()
149+ if byte :
150+ self ._buffer += byte
151+ # if timeout is None, try indefinitely
152+ if timeout is None :
153+ continue
154+ # try next one only if there still is time, and with
155+ # reduced timeout
156+ else :
157+ time_left = timeout - (time .time () - start )
158+ if time_left > 0 :
159+ continue
160+ else :
161+ return None
162+ # return first message
163+ for i in range (len (self ._buffer )):
164+ if self ._buffer [i ] == ord (self ._OK ) or self ._buffer [i ] == ord (self ._ERROR ):
165+ string = self ._buffer [: i + 1 ].decode ()
166+ del self ._buffer [: i + 1 ]
167+ break
168+ return string
169+
170+ def flush (self ):
171+ del self ._buffer [:]
172+ while self .serialPortOrig .in_waiting :
173+ self .serialPortOrig .read ()
174+
124175 def open (self ):
125- self .write ("O" )
176+ self ._write ("O" )
126177
127178 def close (self ):
128- self .write ("C" )
179+ self ._write ("C" )
129180
130181 def _recv_internal (self , timeout ):
131- if timeout != self .serialPortOrig .timeout :
132- self .serialPortOrig .timeout = timeout
133182
134183 canId = None
135184 remote = False
136185 extended = False
137186 frame = []
138187
139- # First read what is already in the receive buffer
140- while (
141- self .serialPortOrig .in_waiting and self .LINE_TERMINATOR not in self ._buffer
142- ):
143- self ._buffer += self .serialPortOrig .read (1 )
144-
145- # If we still don't have a complete message, do a blocking read
146- if self .LINE_TERMINATOR not in self ._buffer :
147- self ._buffer += self .serialPortOrig .read_until (self .LINE_TERMINATOR )
188+ string = self ._read (timeout )
148189
149- if self .LINE_TERMINATOR not in self ._buffer :
150- # Timed out
151- return None , False
152-
153- readStr = self ._buffer .decode ()
154- del self ._buffer [:]
155- if not readStr :
190+ if not string :
156191 pass
157- elif readStr [0 ] == "T" :
192+ elif string [0 ] == "T" :
158193 # extended frame
159- canId = int (readStr [1 :9 ], 16 )
160- dlc = int (readStr [9 ])
194+ canId = int (string [1 :9 ], 16 )
195+ dlc = int (string [9 ])
161196 extended = True
162197 for i in range (0 , dlc ):
163- frame .append (int (readStr [10 + i * 2 : 12 + i * 2 ], 16 ))
164- elif readStr [0 ] == "t" :
198+ frame .append (int (string [10 + i * 2 : 12 + i * 2 ], 16 ))
199+ elif string [0 ] == "t" :
165200 # normal frame
166- canId = int (readStr [1 :4 ], 16 )
167- dlc = int (readStr [4 ])
201+ canId = int (string [1 :4 ], 16 )
202+ dlc = int (string [4 ])
168203 for i in range (0 , dlc ):
169- frame .append (int (readStr [5 + i * 2 : 7 + i * 2 ], 16 ))
170- elif readStr [0 ] == "r" :
204+ frame .append (int (string [5 + i * 2 : 7 + i * 2 ], 16 ))
205+ elif string [0 ] == "r" :
171206 # remote frame
172- canId = int (readStr [1 :4 ], 16 )
173- dlc = int (readStr [4 ])
207+ canId = int (string [1 :4 ], 16 )
208+ dlc = int (string [4 ])
174209 remote = True
175- elif readStr [0 ] == "R" :
210+ elif string [0 ] == "R" :
176211 # remote extended frame
177- canId = int (readStr [1 :9 ], 16 )
178- dlc = int (readStr [9 ])
212+ canId = int (string [1 :9 ], 16 )
213+ dlc = int (string [9 ])
179214 extended = True
180215 remote = True
181-
182216 if canId is not None :
183217 msg = Message (
184218 arbitration_id = canId ,
@@ -194,7 +228,6 @@ def _recv_internal(self, timeout):
194228 def send (self , msg , timeout = None ):
195229 if timeout != self .serialPortOrig .write_timeout :
196230 self .serialPortOrig .write_timeout = timeout
197-
198231 if msg .is_remote_frame :
199232 if msg .is_extended_id :
200233 sendStr = "R%08X%d" % (msg .arbitration_id , msg .dlc )
@@ -205,9 +238,8 @@ def send(self, msg, timeout=None):
205238 sendStr = "T%08X%d" % (msg .arbitration_id , msg .dlc )
206239 else :
207240 sendStr = "t%03X%d" % (msg .arbitration_id , msg .dlc )
208-
209241 sendStr += "" .join (["%02X" % b for b in msg .data ])
210- self .write (sendStr )
242+ self ._write (sendStr )
211243
212244 def shutdown (self ):
213245 self .close ()
@@ -218,3 +250,78 @@ def fileno(self):
218250 return self .serialPortOrig .fileno ()
219251 # Return an invalid file descriptor on Windows
220252 return - 1
253+
254+ def get_version (self , timeout ):
255+ """Get HW and SW version of the slcan interface.
256+
257+ :type timeout: int or None
258+ :param timeout:
259+ seconds to wait for version or None to wait indefinitely
260+
261+ :returns: tuple (hw_version, sw_version)
262+ WHERE
263+ int hw_version is the hardware version or None on timeout
264+ int sw_version is the software version or None on timeout
265+ """
266+ cmd = "V"
267+ self ._write (cmd )
268+
269+ start = time .time ()
270+ time_left = timeout
271+ while True :
272+ string = self ._read (time_left )
273+
274+ if not string :
275+ pass
276+ elif string [0 ] == cmd and len (string ) == 6 :
277+ # convert ASCII coded version
278+ hw_version = int (string [1 :3 ])
279+ sw_version = int (string [3 :5 ])
280+ return hw_version , sw_version
281+ # if timeout is None, try indefinitely
282+ if timeout is None :
283+ continue
284+ # try next one only if there still is time, and with
285+ # reduced timeout
286+ else :
287+ time_left = timeout - (time .time () - start )
288+ if time_left > 0 :
289+ continue
290+ else :
291+ return None , None
292+
293+ def get_serial_number (self , timeout ):
294+ """Get serial number of the slcan interface.
295+
296+ :type timeout: int or None
297+ :param timeout:
298+ seconds to wait for serial number or None to wait indefinitely
299+
300+ :rtype str or None
301+ :return:
302+ None on timeout or a str object.
303+ """
304+ cmd = "N"
305+ self ._write (cmd )
306+
307+ start = time .time ()
308+ time_left = timeout
309+ while True :
310+ string = self ._read (time_left )
311+
312+ if not string :
313+ pass
314+ elif string [0 ] == cmd and len (string ) == 6 :
315+ serial_number = string [1 :- 1 ]
316+ return serial_number
317+ # if timeout is None, try indefinitely
318+ if timeout is None :
319+ continue
320+ # try next one only if there still is time, and with
321+ # reduced timeout
322+ else :
323+ time_left = timeout - (time .time () - start )
324+ if time_left > 0 :
325+ continue
326+ else :
327+ return None
0 commit comments