connection.py 4.0 KB

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