connection.py 4.1 KB

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