acusticSensor.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. import time
  2. import statistics
  3. import math
  4. import threading
  5. import random
  6. import traceback
  7. from sensors.connection import globalArduinoSlave
  8. import logHandler
  9. conn = globalArduinoSlave()
  10. class AcusticSensor:
  11. def __init__(self, conf, ac_queue, calibration_state):
  12. self.conf = conf
  13. self.ac_queue = ac_queue
  14. self.calibration_state = calibration_state
  15. self.field_height = float(conf["field"]["y"])
  16. self.field_width = float(conf["field"]["x"])
  17. self.sensor_y_offset = float(conf["ac_sensor"]["y_offset"])
  18. self.left_sensor_x_offset = float(conf["ac_sensor"]["left_x_offset"])
  19. self.right_sensor_x_offset = float(conf["ac_sensor"]["right_x_offset"])
  20. self.sensor_distance = self.field_width - self.left_sensor_x_offset + self.right_sensor_x_offset
  21. self.sonic_speed = float(conf["ac_sensor"]["sonicspeed"])
  22. self.overhead_left = float(conf["ac_sensor"]["overhead_left"])
  23. self.overhead_right = float(conf["ac_sensor"]["overhead_right"])
  24. self.log_handler = logHandler.get_log_handler()
  25. self.log_handler.log_and_print("start acustic sensor")
  26. # temporary calibration variables
  27. self.time_vals = [[],[]]
  28. self.cal_values = {
  29. "left": [0, 0],
  30. "right": [0, 0]
  31. }
  32. self.n = 0
  33. def start(self):
  34. if not conn.isConnected():
  35. conn.open(port = self.conf["arduino"]["port"])
  36. conn.addRecvCallback(self._readCb)
  37. # generate dummy values until arduino is ready
  38. self.dummyActive = True
  39. dummyThread = threading.Thread(target=self._readCb_dummy)
  40. dummyThread.start()
  41. def start_calibration(self):
  42. self.calibration_state.reset_state()
  43. self.time_vals = [[],[]]
  44. self.calibration_state.next_state()
  45. def stop(self):
  46. self.log_handler.log_and_print("stop acustic sensor")
  47. self.dummyActive = False
  48. conn.close()
  49. def _readCb_dummy(self):
  50. self.log_handler.log_and_print("acustic sensor: generating test values")
  51. while self.dummyActive:
  52. value = (900+random.randint(0,300),900+random.randint(0,300))
  53. value = ((math.sin(self.n)+1)*400+900, (math.cos(self.n)+1)*400+900)
  54. self.n += 0.02
  55. if self.calibration_state.get_state() == self.calibration_state.ACCUMULATING_1:
  56. value = (1541+random.randint(-50,50),2076+random.randint(-50,50))
  57. elif self.calibration_state.get_state() == self.calibration_state.ACCUMULATING_2:
  58. value = (2076+random.randint(-50,50),1541+random.randint(-50,50))
  59. self.calibrate(value)
  60. self.pass_to_gui(self.calculate_position(value) + value)
  61. time.sleep(0.01)
  62. self.log_handler.log_and_print("acustic sensor: disabled test mode")
  63. def _readCb(self, raw):
  64. if self.dummyActive == True:
  65. self.dummyActive = False
  66. value = conn.getAcusticRTTs()
  67. # partially missing values will be ignored
  68. if value[0] >= 0 and value[1] >= 0:
  69. self.calibrate(value)
  70. position = self.calculate_position(value)
  71. if position != None:
  72. self.pass_to_gui(position + value)
  73. def calibrate(self, value):
  74. if self.calibration_state.get_state() == self.calibration_state.ACCUMULATING_1:
  75. self.time_vals[0].append(value[0])
  76. self.time_vals[1].append(value[1])
  77. self.calibration_state.progress = len(self.time_vals[0]) / 2
  78. if len(self.time_vals[0]) >= 100:
  79. self.cal_values["left"][0] = statistics.mean(self.time_vals[0])
  80. self.cal_values["right"][1] = statistics.mean(self.time_vals[1])
  81. self.time_vals = [[],[]]
  82. self.calibration_state.next_state() # signal gui to get next position
  83. elif self.calibration_state.get_state() == self.calibration_state.ACCUMULATING_2:
  84. self.time_vals[0].append(value[0])
  85. self.time_vals[1].append(value[1])
  86. self.calibration_state.progress = 50 + len(self.time_vals[0]) / 2
  87. if len(self.time_vals[0]) >= 100:
  88. self.cal_values["left"][1] = statistics.mean(self.time_vals[0])
  89. self.cal_values["right"][0] = statistics.mean(self.time_vals[1])
  90. # all values have been captured
  91. self.log_handler.log_and_print("calibration measurements:", self.cal_values)
  92. # calculate distances from config
  93. # /| _.-|
  94. # d1 / | d2 _.-` |
  95. # / | y_off + height _.-` | y_off + height
  96. # /___| -____________|
  97. # x_off x_off + width
  98. distance_1 = math.sqrt(self.left_sensor_x_offset**2 + (self.sensor_y_offset + self.field_height)**2 )
  99. distance_2 = math.sqrt((self.left_sensor_x_offset + self.field_width)**2 + (self.sensor_y_offset + self.field_height)**2 )
  100. distancedif = distance_2 - distance_1
  101. timedif = self.cal_values["left"][1] - self.cal_values["left"][0]
  102. # speed of sound in mm/us
  103. sonicspeed_1 = distancedif / timedif
  104. # processing time overhead in us
  105. overhead_1 = statistics.mean((self.cal_values["left"][1] - distance_1/sonicspeed_1, self.cal_values["left"][0] - distance_2/sonicspeed_1))
  106. # same for the second set of values
  107. distance_1 = math.sqrt(self.right_sensor_x_offset**2 + (self.sensor_y_offset + self.field_height)**2 )
  108. distance_2 = math.sqrt((self.right_sensor_x_offset + self.field_width)**2 + (self.sensor_y_offset + self.field_height)**2 )
  109. distancedif = distance_2 - distance_1
  110. timedif = self.cal_values["right"][1] - self.cal_values["right"][0]
  111. sonicspeed_2 = distancedif / timedif
  112. overhead_2 = statistics.mean((self.cal_values["right"][0] - distance_1/sonicspeed_2, self.cal_values["right"][1] - distance_2/sonicspeed_2))
  113. # calculate calibration results
  114. self.sonic_speed = statistics.mean((sonicspeed_1,sonicspeed_2))
  115. self.overhead_left = overhead_1
  116. self.overhead_right = overhead_2
  117. self.log_handler.log_and_print("calibration results:")
  118. self.log_handler.log_and_print(" sonicspeed: {:8.6f} mm/us".format(self.sonic_speed))
  119. self.log_handler.log_and_print(" overhead_left: {:8.3f} us".format(self.overhead_left))
  120. self.log_handler.log_and_print(" overhead_right: {:8.3f} us".format(self.overhead_right))
  121. self.calibration_state.next_state()
  122. def read(self):
  123. value = conn.getAcusticRTTs()
  124. return value
  125. def calculate_position(self,values):
  126. try:
  127. val1, val2 = values
  128. val1 -= self.overhead_left
  129. val2 -= self.overhead_right
  130. distance_left = val1 * self.sonic_speed
  131. distance_right = val2 * self.sonic_speed
  132. # compute intersection of distance circles
  133. x = (self.sensor_distance**2 - distance_right**2 + distance_left**2) / (2*self.sensor_distance) + self.left_sensor_x_offset
  134. if distance_left**2 - x**2 >= 0:
  135. y = math.sqrt(distance_left**2 - x**2) - self.sensor_y_offset
  136. return (x, y)
  137. else:
  138. return None
  139. except Exception as e:
  140. print(values)
  141. traceback.print_exc()
  142. def pass_to_gui(self, data):
  143. self.ac_queue.put(("data", data))