forked from manu-fwi/RR-duino
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserial_bus.py
65 lines (56 loc) · 1.83 KB
/
serial_bus.py
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
import serial,sys
class serial_bus:
def __init__(self,port,baudrate):
self.ser_port = serial.Serial()
self.ser_port.port = port
self.ser_port.baudrate = baudrate
self.ser_port.timeout=0
self.ser_port.write_timeout = 0
self.to_send=b""
self.to_send_pos=0
self.rcv_buffer = b""
def start(self):
if not self.ser_port.is_open:
self.ser_port.open()
def stop(self):
if self.ser_port.is_open:
self.ser_port.close()
def send(self,msg): #msg must be bytes array
if len(self.to_send)>0:
debug("overrun of the sending buffer")
self.to_send=msg
def sending(self):
return len(self.to_send)>0
def set_port(self,port):
self.ser_port.port = port
def set_baud(self,baudrate):
self.ser_port.baudrate = baudrate
def read(self):
if len(self.rcv_buffer)>0:
res = self.rcv_buffer
self.rcv_buffer = b""
return res
else:
return None
def available(self):
return len(self.rcv_buffer)
def process_IO(self):
if self.to_send: #still sending
if self.to_send_pos < len(self.to_send):
debug("sending msg=",self.to_send[self.to_send_pos:])
try:
nb = self.ser_port.write(self.to_send[self.to_send_pos:])
self.to_send_pos += nb
except BaseException:
pass
else:
self.to_send = b""
self.to_send_pos = 0
debug("sending is done")
else: #see if we have received something
try:
self.rcv_buffer += self.ser_port.read()
except BaseException:
pass
def debug(*args,**keywords):
pass