acusticSensor.py 6.6 KB

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