acusticSensor.py 6.4 KB

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