connection.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  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. self.open()
  42. if not self._ser:
  43. time.sleep(10)
  44. def read(self, n=64):
  45. if self._ser:
  46. try:
  47. return self._ser.read(n)
  48. except serial.SerialException:
  49. self._ser = None
  50. return None
  51. else:
  52. self.open()
  53. if not self._ser:
  54. time.sleep(10)
  55. return None
  56. def readline(self):
  57. if self._ser:
  58. try:
  59. return self._ser.readline()
  60. except serial.SerialException:
  61. self._ser = None
  62. return None
  63. else:
  64. self.open()
  65. if not self._ser:
  66. time.sleep(10)
  67. return None
  68. def isConnected(self):
  69. return self._ser != None
  70. def close(self):
  71. if self._ser:
  72. self._ser.close()
  73. self._ser = None
  74. class ArduinoSlave(SerialConnection):
  75. def __init__(self):
  76. super().__init__()
  77. self.sensorData = [0] * 13
  78. self._recvCbs = []
  79. self._t = threading.Thread(target=self._readSensors, args=())
  80. self._t.daemon = True # thread dies when main thread (only non-daemon thread) exits.
  81. def open(self, port = None, baudrate = 1000000):
  82. super().open(port, baudrate)
  83. if not self._t.is_alive():
  84. self._t.start()
  85. def close(self):
  86. super().close()
  87. def getAcusticRTTs(self): # in microseconds
  88. return [
  89. int(self.sensorData[0]) / 16,
  90. int(self.sensorData[1]) / 16
  91. ]
  92. def getMagneticField(self): # in mT
  93. return [
  94. int(self.sensorData[2]) / 1000,
  95. int(self.sensorData[3]) / 1000,
  96. int(self.sensorData[4]) / 1000
  97. ]
  98. def getAccelValues(self):
  99. return [
  100. int(self.sensorData[5]) / 1000,
  101. int(self.sensorData[6]) / 1000,
  102. int(self.sensorData[7]) / 1000
  103. ]
  104. def getGyroValues(self):
  105. return [
  106. int(self.sensorData[8]) / 1000,
  107. int(self.sensorData[9]) / 1000,
  108. int(self.sensorData[10]) / 1000
  109. ]
  110. def getTemperature(self): # in °C
  111. return int(self.sensorData[11]) / 1000
  112. def addRecvCallback(self, cb):
  113. self._recvCbs.append(cb)
  114. def _readSensors(self):
  115. while True:
  116. data = super().readline()
  117. if data and len(data) > 2:
  118. data = str(data, encoding="ASCII", errors="ignore")
  119. vals = data[:-2].split('\t')
  120. if vals[0] == "DATA:" and len(vals) >= 13:
  121. self.sensorData = vals[1:]
  122. for cb in self._recvCbs:
  123. cb(self.sensorData)
  124. else:
  125. print("SERIAL: ", data[:-2])
  126. _conn = None
  127. def globalArduinoSlave():
  128. global _conn
  129. if not _conn:
  130. _conn = ArduinoSlave()
  131. return _conn
  132. if __name__ == "__main__":
  133. arduino = ArduinoSlave()
  134. def cb(x):
  135. print(arduino.getAcusticRTTs(), arduino.getMagneticField(), arduino.getTemperature())
  136. arduino.addRecvCallback(cb)
  137. arduino.open()
  138. while True:
  139. time.sleep(1)