-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmySerial.py
78 lines (72 loc) · 2.3 KB
/
mySerial.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
66
67
68
69
70
71
72
73
74
75
76
77
78
import serial
import sys
import glob
__author__ = 'ruggero'
class MySerial(serial.Serial):
def my_read_line(self, eol=b'\r'):
"""
this function read binary data from the serial
port up to an eol character or no more character on the line
it is a blocking function.
:return:
return all the characters in binary form
"""
len_eol = len(eol)
line = bytearray()
while True:
if self.inWaiting() == 0:
break
c = self.read(1)
if c:
line += c
if line[-len_eol:] == eol:
break
else:
break
return bytes(line)
def inquiring(self, command, rec, save):
"""
this function inquire the serial port with a specific command,
wait for the result, and save it in to a csv file.
It is useful if it run on a different thread.
:param command:
command to send
:param rec:
function to parse the received data
:param save:
csv writer for saving purpose
:return:
None
"""
self.write(command)
data = rec(self.my_read_line())
print(str(data))
data = [i[1] for i in data]
save.writerow(data)
return None
@staticmethod
def serial_ports():
""" Lists serial port names
:raises EnvironmentError:
On unsupported or unknown platforms
:returns:
A list of the serial ports available on the system
"""
if sys.platform.startswith('win'):
ports = ['COM%s' % (i + 1) for i in range(256)]
elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
# this excludes your current terminal "/dev/tty"
ports = glob.glob('/dev/tty[A-Za-z]*')
elif sys.platform.startswith('darwin'):
ports = glob.glob('/dev/tty.*')
else:
raise EnvironmentError('Unsupported platform')
result = []
for port in ports:
try:
s = serial.Serial(port)
s.close()
result.append(port)
except (OSError, serial.SerialException):
pass
return result