acusticSensor.py 7.0 KB

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