acusticSensor.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  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. self.pass_to_gui(self.calculate_position(value) + value)
  65. def calibrate(self, value):
  66. if self.calibration_state.get_state() == self.calibration_state.ACCUMULATING_1:
  67. self.time_vals[0].append(value[0])
  68. self.time_vals[1].append(value[1])
  69. self.calibration_state.progress = len(self.time_vals[0]) / 2
  70. if len(self.time_vals[0]) >= 100:
  71. self.cal_values["left"][0] = statistics.mean(self.time_vals[0])
  72. self.cal_values["right"][1] = statistics.mean(self.time_vals[1])
  73. self.time_vals = [[],[]]
  74. self.calibration_state.next_state() # signal gui to get next position
  75. elif self.calibration_state.get_state() == self.calibration_state.ACCUMULATING_2:
  76. self.time_vals[0].append(value[0])
  77. self.time_vals[1].append(value[1])
  78. self.calibration_state.progress = 50 + len(self.time_vals[0]) / 2
  79. if len(self.time_vals[0]) >= 100:
  80. self.cal_values["left"][1] = statistics.mean(self.time_vals[0])
  81. self.cal_values["right"][0] = statistics.mean(self.time_vals[1])
  82. # all values have been captured
  83. print("calibration measurements:", self.cal_values)
  84. # calculate distances from config
  85. # /| _.-|
  86. # d1 / | d2 _.-` |
  87. # / | y_off + height _.-` | y_off + height
  88. # /___| -____________|
  89. # x_off x_off + width
  90. distance_1 = math.sqrt(self.left_sensor_x_offset**2 + (self.sensor_y_offset + self.field_height)**2 )
  91. distance_2 = math.sqrt((self.left_sensor_x_offset + self.field_width)**2 + (self.sensor_y_offset + self.field_height)**2 )
  92. distancedif = distance_2 - distance_1
  93. timedif = self.cal_values["left"][1] - self.cal_values["left"][0]
  94. # speed of sound in mm/us
  95. sonicspeed_1 = distancedif / timedif
  96. # processing time overhead in us
  97. overhead_1 = statistics.mean((self.cal_values["left"][1] - distance_1/sonicspeed_1, self.cal_values["left"][0] - distance_2/sonicspeed_1))
  98. # same for the second set of values
  99. distance_1 = math.sqrt(self.right_sensor_x_offset**2 + (self.sensor_y_offset + self.field_height)**2 )
  100. distance_2 = math.sqrt((self.right_sensor_x_offset + self.field_width)**2 + (self.sensor_y_offset + self.field_height)**2 )
  101. distancedif = distance_2 - distance_1
  102. timedif = self.cal_values["right"][1] - self.cal_values["right"][0]
  103. sonicspeed_2 = distancedif / timedif
  104. overhead_2 = statistics.mean((self.cal_values["right"][0] - distance_1/sonicspeed_2, self.cal_values["right"][1] - distance_2/sonicspeed_2))
  105. # calculate calibration results
  106. self.sonic_speed = statistics.mean((sonicspeed_1,sonicspeed_2))
  107. self.overhead_left = overhead_1
  108. self.overhead_right = overhead_2
  109. print("calibration results:")
  110. print(" sonicspeed: {:8.6f} mm/us".format(self.sonic_speed))
  111. print(" overhead_left: {:8.3f} us".format(self.overhead_left))
  112. print(" overhead_right: {:8.3f} us".format(self.overhead_right))
  113. self.calibration_state.next_state()
  114. def read(self):
  115. value = conn.getAcusticRTTs()
  116. return value
  117. def calculate_position(self,values):
  118. try:
  119. val1, val2 = values
  120. val1 -= self.overhead_left
  121. val2 -= self.overhead_right
  122. distance_left = val1 * self.sonic_speed
  123. distance_right = val2 * self.sonic_speed
  124. # compute intersection of distance circles
  125. x = (self.sensor_distance**2 - distance_right**2 + distance_left**2) / (2*self.sensor_distance) + self.left_sensor_x_offset
  126. y = math.sqrt(max(distance_left**2 - x**2, 0)) - self.sensor_y_offset
  127. return (x, y)
  128. except Exception as e:
  129. print(values)
  130. traceback.print_exc()
  131. def pass_to_gui(self, data):
  132. self.ac_queue.put(("data", data))