acusticSensor.py 7.5 KB

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