-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSerial_Comm.py
98 lines (86 loc) · 3.38 KB
/
Serial_Comm.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import serial, time
import serial.tools.list_ports
class serialComm():
def __init__(self):
self.commPort = None
self.connection = 0
self.listPorts = list()
self.connectedPort = None
def auto_establish_comm(self):
self.find_com_port()
if self.commPort is not None:
self.connectedPort = self.commPort
# print(self.connectedPort)
# print("Communication port found: ",self.connectedPort)
try:
self.serialcom = serial.Serial(self.connectedPort, 9600)
# print("Establishing communication at port: ",self.connectedPort)
self.serialcom.timeout = 1
self.connection = 1
except serial.serialutil.SerialException:
self.serialcom.close()
else:
self.connectedPort = None
self.connection = 0
# print("No communication port found")
def change_comPort(self):
if self.connectedPort is None:
self.auto_establish_comm()
else:
self.find_com_port()
if len(self.listPorts)>1:
try:
# self.serialcom.close()
index = self.listPorts.index(self.connectedPort)
if len(self.listPorts) == (index+1):
index = -1
self.connectedPort = self.listPorts[index+1]
# print("New Communication port selected: ",self.connectedPort)
try:
self.serialcom = serial.Serial(self.connectedPort, 9600)
# print("Establishing communication at new port: ",self.connectedPort)
self.serialcom.timeout = 1
self.connection = 1
time.sleep(.5)
except serial.serialutil.SerialException:
self.serialcom.close()
except ValueError:
self.connectedPort = None
elif len(self.listPorts) == 1:
self.connectedPort = self.listPorts[0]
else:
self.connectedPort = None
self.connection = 0
# print("No new communication port found")
def find_com_port(self):
self.listPorts.clear()
portData = serial.tools.list_ports.comports()
if len(portData)>0:
for i in portData:
port = str(i).split()
self.listPorts.append(port[0])
# print(self.listPorts)
try:
self.listPorts.remove('/dev/ttyAMA0')
except ValueError:
pass
if len(self.listPorts)>0:
self.commPort = self.listPorts[0]
return self.listPorts
else:
self.commPort = None
return None
else:
self.commPort = None
return None
def communicate(self,data):
try:
self.serialcom.write(data.encode())
time.sleep(0.5)
return True
except serial.serialutil.SerialException:
# print("Communication port disconnected")
return False
if __name__ == "__main__":
a = serialComm()
print(a.find_com_port())