connection.py 3.8 KB

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