|
@@ -2,6 +2,7 @@ import threading
|
|
|
import time
|
|
|
|
|
|
import serial
|
|
|
+import serial.tools.list_ports
|
|
|
|
|
|
|
|
|
class SerialConnection:
|
|
@@ -11,36 +12,28 @@ class SerialConnection:
|
|
|
|
|
|
# try connecting to an available port
|
|
|
def open(self, port = None, baudrate = 1000000):
|
|
|
- self.port = port
|
|
|
+ if port != None:
|
|
|
+ self.port = port
|
|
|
|
|
|
- if self.port == None:
|
|
|
- for port in ["/dev/ttyUSB{}".format(p) for p in range(4)]:
|
|
|
- try:
|
|
|
- self._ser = serial.Serial(port, baudrate)
|
|
|
- print("SERIAL: connected to " + port)
|
|
|
- self.port = port
|
|
|
- break
|
|
|
- except serial.SerialException:
|
|
|
- pass
|
|
|
-
|
|
|
- if self.port == None:
|
|
|
- for port in ["COM{}".format(p) for p in range(3,20)]:
|
|
|
+ if self.port:
|
|
|
+ try:
|
|
|
+ self._ser = serial.Serial(self.port, baudrate)
|
|
|
+ print("SERIAL: connected to " + self.port)
|
|
|
+ except serial.SerialException as e:
|
|
|
+ print("SERIAL:", e)
|
|
|
+
|
|
|
+ else:
|
|
|
+ for port, name, _ in serial.tools.list_ports.comports():
|
|
|
try:
|
|
|
self._ser = serial.Serial(port, baudrate)
|
|
|
- print("SERIAL: connected to " + port)
|
|
|
+ print("SERIAL: connected to " + port + ", name: " + name)
|
|
|
self.port = port
|
|
|
break
|
|
|
- except serial.SerialException:
|
|
|
- pass
|
|
|
- else:
|
|
|
- try:
|
|
|
- self._ser = serial.Serial(self.port, baudrate)
|
|
|
- print("SERIAL: connected to " + self.port)
|
|
|
- except serial.SerialException:
|
|
|
- pass
|
|
|
+ except serial.SerialException as e:
|
|
|
+ print("SERIAL:", e)
|
|
|
|
|
|
if not self._ser:
|
|
|
- print("SERIAL: connection failed")
|
|
|
+ print("SERIAL: no device available")
|
|
|
|
|
|
def send(self, bytes):
|
|
|
if self._ser:
|
|
@@ -57,9 +50,13 @@ class SerialConnection:
|
|
|
if self._ser:
|
|
|
try:
|
|
|
return self._ser.read(n)
|
|
|
- except AttributeError:
|
|
|
+ except AttributeError as e:
|
|
|
+ print("SERIAL:", e)
|
|
|
return None
|
|
|
- except serial.SerialException:
|
|
|
+ except serial.SerialException as e:
|
|
|
+ print("SERIAL:", e)
|
|
|
+ if self._ser.isOpen():
|
|
|
+ self._ser.close()
|
|
|
self._ser = None
|
|
|
return None
|
|
|
else:
|
|
@@ -71,9 +68,13 @@ class SerialConnection:
|
|
|
if self._ser:
|
|
|
try:
|
|
|
return self._ser.readline()
|
|
|
- except AttributeError:
|
|
|
+ except AttributeError as e:
|
|
|
+ print("SERIAL:", e)
|
|
|
return None
|
|
|
- except serial.SerialException:
|
|
|
+ except serial.SerialException as e:
|
|
|
+ print("SERIAL:", e)
|
|
|
+ if self._ser.isOpen():
|
|
|
+ self._ser.close()
|
|
|
self._ser = None
|
|
|
return None
|
|
|
else:
|