connection.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. import threading, time, serial
  2. class SerialConnection:
  3. def __init__(self):
  4. self._ser = None
  5. self.port = None
  6. def open(self, port = None, baudrate = 1000000):
  7. self.port = port
  8. if self.port == None:
  9. for port in ["/dev/ttyUSB{}".format(p) for p in range(4)]:
  10. try:
  11. self._ser = serial.Serial(port, baudrate)
  12. print("SERIAL: connected to " + port)
  13. self.port = port
  14. break
  15. except serial.SerialException:
  16. pass
  17. if self.port == None:
  18. for port in ["COM{}".format(p) for p in range(3,20)]:
  19. try:
  20. self._ser = serial.Serial(port, baudrate)
  21. print("SERIAL: connected to " + port)
  22. self.port = port
  23. break
  24. except serial.SerialException:
  25. pass
  26. else:
  27. try:
  28. self._ser = serial.Serial(self.port, baudrate)
  29. print("SERIAL: connected to " + self.port)
  30. except serial.SerialException:
  31. pass
  32. if not self._ser:
  33. print("SERIAL: connection failed")
  34. def send(self, bytes):
  35. if self._ser:
  36. try:
  37. return self._ser.write(bytes)
  38. except serial.SerialException:
  39. self._ser = None
  40. else:
  41. time.sleep(10)
  42. self.open()
  43. return None
  44. def read(self, n=64):
  45. if self._ser:
  46. try:
  47. return self._ser.read(n)
  48. except AttributeError:
  49. return None
  50. except serial.SerialException:
  51. self._ser = None
  52. return None
  53. else:
  54. time.sleep(10)
  55. self.open()
  56. return None
  57. def readline(self):
  58. if self._ser:
  59. try:
  60. return self._ser.readline()
  61. except AttributeError:
  62. return None
  63. except serial.SerialException:
  64. self._ser = None
  65. return None
  66. else:
  67. time.sleep(10)
  68. self.open()
  69. return None
  70. def isConnected(self):
  71. return self._ser != None
  72. def close(self):
  73. if self._ser:
  74. self._ser.close()
  75. self._ser = None
  76. class ArduinoSlave(SerialConnection):
  77. def __init__(self):
  78. super().__init__()
  79. self.sensorData = [0] * 13
  80. self._recvCbs = []
  81. self._t = threading.Thread(target=self._readSensors, args=())
  82. self._t.daemon = True # thread dies when main thread (only non-daemon thread) exits.
  83. def open(self, port = None, baudrate = 1000000):
  84. super().open(port, baudrate)
  85. if not self._t.is_alive():
  86. self._t.start()
  87. def close(self):
  88. super().close()
  89. def getAcusticRTTs(self): # in microseconds
  90. return (
  91. int(self.sensorData[0]) / 16,
  92. int(self.sensorData[1]) / 16
  93. )
  94. def getMagneticField(self): # in mT
  95. return (
  96. int(self.sensorData[2]) / 1000,
  97. int(self.sensorData[3]) / 1000,
  98. int(self.sensorData[4]) / 1000
  99. )
  100. def getAccelValues(self):
  101. return (
  102. int(self.sensorData[5]) / 1000,
  103. int(self.sensorData[6]) / 1000,
  104. int(self.sensorData[7]) / 1000
  105. )
  106. def getGyroValues(self):
  107. return (
  108. int(self.sensorData[8]) / 1000,
  109. int(self.sensorData[9]) / 1000,
  110. int(self.sensorData[10]) / 1000
  111. )
  112. def getTemperature(self): # in °C
  113. return int(self.sensorData[11]) / 1000
  114. def addRecvCallback(self, cb):
  115. self._recvCbs.append(cb)
  116. def _readSensors(self):
  117. while True:
  118. data = super().readline()
  119. if data and len(data) > 2:
  120. data = str(data, encoding="ASCII", errors="ignore")
  121. vals = data[:-2].split('\t')
  122. if vals[0] == "DATA:" and len(vals) >= 13:
  123. self.sensorData = vals[1:]
  124. for cb in self._recvCbs:
  125. cb(self.sensorData)
  126. else:
  127. print("SERIAL: ", data[:-2])
  128. _conn = None
  129. def globalArduinoSlave():
  130. global _conn
  131. if not _conn:
  132. _conn = ArduinoSlave()
  133. return _conn
  134. if __name__ == "__main__":
  135. arduino = ArduinoSlave()
  136. def cb(x):
  137. print(arduino.getAcusticRTTs(), arduino.getMagneticField(), arduino.getTemperature())
  138. arduino.addRecvCallback(cb)
  139. arduino.open()
  140. while True:
  141. time.sleep(1)