-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserial_functions.py
More file actions
70 lines (58 loc) · 2.18 KB
/
serial_functions.py
File metadata and controls
70 lines (58 loc) · 2.18 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
import serial
import serial.tools.list_ports
from serial import SerialTimeoutException
from pubsub import pub
import settings
def serial_ports():
# Lists serial port names
comlist = serial.tools.list_ports.comports()
available_ports = []
for element in comlist:
available_ports.append(element.device)
pub.sendMessage("AvailablePorts", choices=available_ports)
class SerialConnection:
def __init__(self):
self.ser_port = None
def send_serial_msg(self, interface, msg):
# Send a serial message
if settings.last_interface == interface:
if self.ser_port is not None:
if self.ser_port.isOpen():
self.ser_port.write(bytearray.fromhex(msg))
else:
self.open_serial(interface)
if self.ser_port is not None:
if self.ser_port.isOpen():
try:
self.ser_port.write(bytearray.fromhex(msg))
except SerialTimeoutException as e:
print(e)
except Exception as e:
print(e)
else:
settings.last_interface = interface
self.ser_port.close()
self.open_serial(interface)
if self.ser_port is not None:
if self.ser_port.isOpen():
try:
self.ser_port.write(bytearray.fromhex(msg))
except SerialTimeoutException as e:
print(e)
except Exception as e:
print(e)
def open_serial(self, interface):
# Opens a specified serial port interface
try:
self.ser_port = serial.Serial(interface, int(settings.last_baud), write_timeout=0.5)
except Exception as e:
print(e)
print("Serial Connection Failed")
def close_serial(self):
try:
if self.ser_port is not None:
if self.ser_port.isOpen():
self.ser_port.close()
except Exception as e:
print(e)
persistent_serial_connection = SerialConnection()