acusticSensor.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  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.add_item("start ac_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. print("stop acoustic sensor")
  47. self.dummyActive = False
  48. conn.close()
  49. def _readCb_dummy(self):
  50. while self.dummyActive:
  51. value = (900+random.randint(0,300),900+random.randint(0,300))
  52. value = ((math.sin(self.n)+1)*400+900, (math.cos(self.n)+1)*400+900)
  53. self.n += 0.02
  54. if self.calibration_state.get_state() == self.calibration_state.ACCUMULATING_1:
  55. value = (1541+random.randint(-50,50),2076+random.randint(-50,50))
  56. elif self.calibration_state.get_state() == self.calibration_state.ACCUMULATING_2:
  57. value = (2076+random.randint(-50,50),1541+random.randint(-50,50))
  58. self.calibrate(value)
  59. self.pass_to_gui(self.calculate_position(value) + value)
  60. time.sleep(0.01)
  61. def _readCb(self, raw):
  62. self.dummyActive = False
  63. value = conn.getAcusticRTTs()
  64. # partially missing values will be ignored
  65. if value[0] >= 0 and value[1] >= 0:
  66. self.calibrate(value)
  67. position = self.calculate_position(value)
  68. if position != None:
  69. self.pass_to_gui(position + value)
  70. def calibrate(self, value):
  71. if self.calibration_state.get_state() == self.calibration_state.ACCUMULATING_1:
  72. self.time_vals[0].append(value[0])
  73. self.time_vals[1].append(value[1])
  74. self.calibration_state.progress = len(self.time_vals[0]) / 2
  75. if len(self.time_vals[0]) >= 100:
  76. self.cal_values["left"][0] = statistics.mean(self.time_vals[0])
  77. self.cal_values["right"][1] = statistics.mean(self.time_vals[1])
  78. self.time_vals = [[],[]]
  79. self.calibration_state.next_state() # signal gui to get next position
  80. elif self.calibration_state.get_state() == self.calibration_state.ACCUMULATING_2:
  81. self.time_vals[0].append(value[0])
  82. self.time_vals[1].append(value[1])
  83. self.calibration_state.progress = 50 + len(self.time_vals[0]) / 2
  84. if len(self.time_vals[0]) >= 100:
  85. self.cal_values["left"][1] = statistics.mean(self.time_vals[0])
  86. self.cal_values["right"][0] = statistics.mean(self.time_vals[1])
  87. # all values have been captured
  88. print("calibration measurements:", self.cal_values)
  89. self.log_handler.add_item("calibration measurements:", self.cal_values)
  90. # calculate distances from config
  91. # /| _.-|
  92. # d1 / | d2 _.-` |
  93. # / | y_off + height _.-` | y_off + height
  94. # /___| -____________|
  95. # x_off x_off + width
  96. distance_1 = math.sqrt(self.left_sensor_x_offset**2 + (self.sensor_y_offset + self.field_height)**2 )
  97. distance_2 = math.sqrt((self.left_sensor_x_offset + self.field_width)**2 + (self.sensor_y_offset + self.field_height)**2 )
  98. distancedif = distance_2 - distance_1
  99. timedif = self.cal_values["left"][1] - self.cal_values["left"][0]
  100. # speed of sound in mm/us
  101. sonicspeed_1 = distancedif / timedif
  102. # processing time overhead in us
  103. overhead_1 = statistics.mean((self.cal_values["left"][1] - distance_1/sonicspeed_1, self.cal_values["left"][0] - distance_2/sonicspeed_1))
  104. # same for the second set of values
  105. distance_1 = math.sqrt(self.right_sensor_x_offset**2 + (self.sensor_y_offset + self.field_height)**2 )
  106. distance_2 = math.sqrt((self.right_sensor_x_offset + self.field_width)**2 + (self.sensor_y_offset + self.field_height)**2 )
  107. distancedif = distance_2 - distance_1
  108. timedif = self.cal_values["right"][1] - self.cal_values["right"][0]
  109. sonicspeed_2 = distancedif / timedif
  110. overhead_2 = statistics.mean((self.cal_values["right"][0] - distance_1/sonicspeed_2, self.cal_values["right"][1] - distance_2/sonicspeed_2))
  111. # calculate calibration results
  112. self.sonic_speed = statistics.mean((sonicspeed_1,sonicspeed_2))
  113. self.overhead_left = overhead_1
  114. self.overhead_right = overhead_2
  115. print("calibration results:")
  116. print(" sonicspeed: {:8.6f} mm/us".format(self.sonic_speed))
  117. print(" overhead_left: {:8.3f} us".format(self.overhead_left))
  118. print(" overhead_right: {:8.3f} us".format(self.overhead_right))
  119. self.log_handler.add_item("calibration results:")
  120. self.log_handler.add_item(" sonicspeed: {:8.6f} mm/us".format(self.sonic_speed))
  121. self.log_handler.add_item(" overhead_left: {:8.3f} us".format(self.overhead_left))
  122. self.log_handler.add_item(" overhead_right: {:8.3f} us".format(self.overhead_right))
  123. self.calibration_state.next_state()
  124. def read(self):
  125. value = conn.getAcusticRTTs()
  126. return value
  127. def calculate_position(self,values):
  128. try:
  129. val1, val2 = values
  130. val1 -= self.overhead_left
  131. val2 -= self.overhead_right
  132. distance_left = val1 * self.sonic_speed
  133. distance_right = val2 * self.sonic_speed
  134. # compute intersection of distance circles
  135. x = (self.sensor_distance**2 - distance_right**2 + distance_left**2) / (2*self.sensor_distance) + self.left_sensor_x_offset
  136. if distance_left**2 - x**2 >= 0:
  137. y = math.sqrt(distance_left**2 - x**2) - self.sensor_y_offset
  138. return (x, y)
  139. else:
  140. return None
  141. except Exception as e:
  142. print(values)
  143. traceback.print_exc()
  144. def pass_to_gui(self, data):
  145. self.ac_queue.put(("data", data))