connection.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. class SerialConnection:
  2. def __init__(self):
  3. self._ser = None
  4. self.port = None
  5. def open(self, port = None, baudrate = 115200):
  6. self.port = port
  7. if self.port == None:
  8. for port in ["/dev/ttyUSB{}".format(p) for p in range(4)]:
  9. try:
  10. self._ser = serial.Serial(port, baudrate)
  11. print("connected to " + port)
  12. self.port = port
  13. break
  14. except serial.SerialException:
  15. pass
  16. if self.port == None:
  17. for port in ["COM{}".format(p) for p in range(3,20)]:
  18. try:
  19. self._ser = serial.Serial(port, baudrate)
  20. print("connected to " + port)
  21. self.port = port
  22. break
  23. except serial.SerialException:
  24. pass
  25. else:
  26. try:
  27. self._ser = serial.Serial(self.port, baudrate)
  28. print("connected to " + self.port)
  29. except serial.SerialException:
  30. pass
  31. else:
  32. print("connection to port {} failed".format(port))
  33. def send(self, bytes):
  34. if self._ser:
  35. try:
  36. return self._ser.write(bytes)
  37. except serial.SerialException:
  38. self._ser = None
  39. if not self._ser:
  40. self.open()
  41. if not self._ser:
  42. time.sleep(30)
  43. def read(self, n=64):
  44. if self._ser:
  45. try:
  46. if self._ser.in_waiting:
  47. return self._ser.read(n)
  48. except serial.SerialException:
  49. self._ser = None
  50. if not self._ser:
  51. self.open()
  52. def isConnected(self):
  53. return self._ser != None
  54. def close(self):
  55. if self._ser:
  56. self._ser.close()
  57. class ArduinoSlave(SerialConnection):
  58. def __init__(self):
  59. self.sensorData = (0) * 12
  60. def open(self):
  61. #thread: sensorData = read()
  62. pass
  63. def getAcusticRTTs(self):
  64. return self.sensorData[0:2]
  65. def getMagneticField(self):
  66. return self.sensorData[2:5]