001// Copyright (c) FIRST and other WPILib contributors.
002// Open Source Software; you can modify and/or share it under the terms of
003// the WPILib BSD license file in the root directory of this project.
004
005package edu.wpi.first.wpilibj;
006
007import static edu.wpi.first.util.ErrorMessages.requireNonNullParam;
008
009import edu.wpi.first.hal.FRCNetComm.tResourceType;
010import edu.wpi.first.hal.HAL;
011import edu.wpi.first.hal.SimBoolean;
012import edu.wpi.first.hal.SimDevice;
013import edu.wpi.first.hal.SimDevice.Direction;
014import edu.wpi.first.hal.SimDouble;
015import edu.wpi.first.util.sendable.Sendable;
016import edu.wpi.first.util.sendable.SendableBuilder;
017import edu.wpi.first.util.sendable.SendableRegistry;
018import java.util.ArrayList;
019import java.util.List;
020
021/**
022 * Ultrasonic rangefinder class. The Ultrasonic rangefinder measures absolute distance based on the
023 * round-trip time of a ping generated by the controller. These sensors use two transducers, a
024 * speaker and a microphone both tuned to the ultrasonic range. A common ultrasonic sensor, the
025 * Daventech SRF04 requires a short pulse to be generated on a digital channel. This causes the
026 * chirp to be emitted. A second line becomes high as the ping is transmitted and goes low when the
027 * echo is received. The time that the line is high determines the round trip distance (time of
028 * flight).
029 */
030public class Ultrasonic implements Sendable, AutoCloseable {
031  // Time (sec) for the ping trigger pulse.
032  private static final double kPingTime = 10 * 1e-6;
033  private static final double kSpeedOfSoundInchesPerSec = 1130.0 * 12.0;
034  // ultrasonic sensor list
035  private static final List<Ultrasonic> m_sensors = new ArrayList<>();
036  // automatic round robin mode
037  private static volatile boolean m_automaticEnabled;
038  private DigitalInput m_echoChannel;
039  private DigitalOutput m_pingChannel;
040  private final boolean m_allocatedChannels;
041  private boolean m_enabled;
042  private Counter m_counter;
043  // task doing the round-robin automatic sensing
044  private static Thread m_task;
045  private static int m_instances;
046
047  private SimDevice m_simDevice;
048  private SimBoolean m_simRangeValid;
049  private SimDouble m_simRange;
050
051  /**
052   * Background task that goes through the list of ultrasonic sensors and pings each one in turn.
053   * The counter is configured to read the timing of the returned echo pulse.
054   *
055   * <p><b>DANGER WILL ROBINSON, DANGER WILL ROBINSON:</b> This code runs as a task and assumes that
056   * none of the ultrasonic sensors will change while it's running. If one does, then this will
057   * certainly break. Make sure to disable automatic mode before changing anything with the
058   * sensors!!
059   */
060  private static class UltrasonicChecker extends Thread {
061    @Override
062    public synchronized void run() {
063      while (m_automaticEnabled) {
064        for (Ultrasonic sensor : m_sensors) {
065          if (!m_automaticEnabled) {
066            break;
067          }
068
069          if (sensor.isEnabled()) {
070            sensor.m_pingChannel.pulse(kPingTime); // do the ping
071          }
072
073          Timer.delay(0.1); // wait for ping to return
074        }
075      }
076    }
077  }
078
079  /**
080   * Initialize the Ultrasonic Sensor. This is the common code that initializes the ultrasonic
081   * sensor given that there are two digital I/O channels allocated. If the system was running in
082   * automatic mode (round-robin) when the new sensor is added, it is stopped, the sensor is added,
083   * then automatic mode is restored.
084   */
085  private synchronized void initialize() {
086    m_simDevice = SimDevice.create("Ultrasonic", m_echoChannel.getChannel());
087    if (m_simDevice != null) {
088      m_simRangeValid = m_simDevice.createBoolean("Range Valid", Direction.kInput, true);
089      m_simRange = m_simDevice.createDouble("Range (in)", Direction.kInput, 0.0);
090      m_pingChannel.setSimDevice(m_simDevice);
091      m_echoChannel.setSimDevice(m_simDevice);
092    }
093    final boolean originalMode = m_automaticEnabled;
094    setAutomaticMode(false); // kill task when adding a new sensor
095    m_sensors.add(this);
096
097    m_counter = new Counter(m_echoChannel); // set up counter for this
098    SendableRegistry.addChild(this, m_counter);
099    // sensor
100    m_counter.setMaxPeriod(1.0);
101    m_counter.setSemiPeriodMode(true);
102    m_counter.reset();
103    m_enabled = true; // make it available for round-robin scheduling
104    setAutomaticMode(originalMode);
105
106    m_instances++;
107    HAL.report(tResourceType.kResourceType_Ultrasonic, m_instances);
108    SendableRegistry.addLW(this, "Ultrasonic", m_echoChannel.getChannel());
109  }
110
111  /**
112   * Returns the echo channel.
113   *
114   * @return The echo channel.
115   */
116  public int getEchoChannel() {
117    return m_echoChannel.getChannel();
118  }
119
120  /**
121   * Create an instance of the Ultrasonic Sensor. This is designed to support the Daventech SRF04
122   * and Vex ultrasonic sensors.
123   *
124   * @param pingChannel The digital output channel that sends the pulse to initiate the sensor
125   *     sending the ping.
126   * @param echoChannel The digital input channel that receives the echo. The length of time that
127   *     the echo is high represents the round trip time of the ping, and the distance.
128   */
129  @SuppressWarnings("this-escape")
130  public Ultrasonic(final int pingChannel, final int echoChannel) {
131    m_pingChannel = new DigitalOutput(pingChannel);
132    m_echoChannel = new DigitalInput(echoChannel);
133    SendableRegistry.addChild(this, m_pingChannel);
134    SendableRegistry.addChild(this, m_echoChannel);
135    m_allocatedChannels = true;
136    initialize();
137  }
138
139  /**
140   * Create an instance of an Ultrasonic Sensor from a DigitalInput for the echo channel and a
141   * DigitalOutput for the ping channel.
142   *
143   * @param pingChannel The digital output object that starts the sensor doing a ping. Requires a
144   *     10uS pulse to start.
145   * @param echoChannel The digital input object that times the return pulse to determine the range.
146   */
147  @SuppressWarnings("this-escape")
148  public Ultrasonic(DigitalOutput pingChannel, DigitalInput echoChannel) {
149    requireNonNullParam(pingChannel, "pingChannel", "Ultrasonic");
150    requireNonNullParam(echoChannel, "echoChannel", "Ultrasonic");
151
152    m_allocatedChannels = false;
153    m_pingChannel = pingChannel;
154    m_echoChannel = echoChannel;
155    initialize();
156  }
157
158  /**
159   * Destructor for the ultrasonic sensor. Delete the instance of the ultrasonic sensor by freeing
160   * the allocated digital channels. If the system was in automatic mode (round-robin), then it is
161   * stopped, then started again after this sensor is removed (provided this wasn't the last
162   * sensor).
163   */
164  @Override
165  public synchronized void close() {
166    SendableRegistry.remove(this);
167    final boolean wasAutomaticMode = m_automaticEnabled;
168    setAutomaticMode(false);
169    if (m_allocatedChannels) {
170      if (m_pingChannel != null) {
171        m_pingChannel.close();
172      }
173      if (m_echoChannel != null) {
174        m_echoChannel.close();
175      }
176    }
177
178    if (m_counter != null) {
179      m_counter.close();
180      m_counter = null;
181    }
182
183    m_pingChannel = null;
184    m_echoChannel = null;
185    synchronized (m_sensors) {
186      m_sensors.remove(this);
187    }
188    if (!m_sensors.isEmpty() && wasAutomaticMode) {
189      setAutomaticMode(true);
190    }
191
192    if (m_simDevice != null) {
193      m_simDevice.close();
194      m_simDevice = null;
195    }
196  }
197
198  /**
199   * Turn Automatic mode on/off for all sensors.
200   *
201   * <p>When in Automatic mode, all sensors will fire in round-robin, waiting a set time between
202   * each sensor.
203   *
204   * @param enabling Set to true if round-robin scheduling should start for all the ultrasonic
205   *     sensors. This scheduling method assures that the sensors are non-interfering because no two
206   *     sensors fire at the same time. If another scheduling algorithm is preferred, it can be
207   *     implemented by pinging the sensors manually and waiting for the results to come back.
208   */
209  public static synchronized void setAutomaticMode(boolean enabling) {
210    if (enabling == m_automaticEnabled) {
211      return; // ignore the case of no change
212    }
213    m_automaticEnabled = enabling;
214
215    if (enabling) {
216      /* Clear all the counters so no data is valid. No synchronization is
217       * needed because the background task is stopped.
218       */
219      for (Ultrasonic u : m_sensors) {
220        u.m_counter.reset();
221      }
222
223      // Start round robin task
224      m_task = new UltrasonicChecker();
225      m_task.start();
226    } else {
227      if (m_task != null) {
228        // Wait for background task to stop running
229        try {
230          m_task.join();
231          m_task = null;
232        } catch (InterruptedException ex) {
233          Thread.currentThread().interrupt();
234          ex.printStackTrace();
235        }
236      }
237
238      /* Clear all the counters (data now invalid) since automatic mode is
239       * disabled. No synchronization is needed because the background task is
240       * stopped.
241       */
242      for (Ultrasonic u : m_sensors) {
243        u.m_counter.reset();
244      }
245    }
246  }
247
248  /**
249   * Single ping to ultrasonic sensor. Send out a single ping to the ultrasonic sensor. This only
250   * works if automatic (round-robin) mode is disabled. A single ping is sent out, and the counter
251   * should count the semi-period when it comes in. The counter is reset to make the current value
252   * invalid.
253   */
254  public void ping() {
255    setAutomaticMode(false); // turn off automatic round-robin if pinging
256    // single sensor
257    m_counter.reset(); // reset the counter to zero (invalid data now)
258    // do the ping to start getting a single range
259    m_pingChannel.pulse(kPingTime);
260  }
261
262  /**
263   * Check if there is a valid range measurement. The ranges are accumulated in a counter that will
264   * increment on each edge of the echo (return) signal. If the count is not at least 2, then the
265   * range has not yet been measured, and is invalid.
266   *
267   * @return true if the range is valid
268   */
269  public boolean isRangeValid() {
270    if (m_simRangeValid != null) {
271      return m_simRangeValid.get();
272    }
273    return m_counter.get() > 1;
274  }
275
276  /**
277   * Get the range in inches from the ultrasonic sensor. If there is no valid value yet, i.e. at
278   * least one measurement hasn't completed, then return 0.
279   *
280   * @return double Range in inches of the target returned from the ultrasonic sensor.
281   */
282  public double getRangeInches() {
283    if (isRangeValid()) {
284      if (m_simRange != null) {
285        return m_simRange.get();
286      }
287      return m_counter.getPeriod() * kSpeedOfSoundInchesPerSec / 2.0;
288    } else {
289      return 0;
290    }
291  }
292
293  /**
294   * Get the range in millimeters from the ultrasonic sensor. If there is no valid value yet, i.e.
295   * at least one measurement hasn't completed, then return 0.
296   *
297   * @return double Range in millimeters of the target returned by the ultrasonic sensor.
298   */
299  public double getRangeMM() {
300    return getRangeInches() * 25.4;
301  }
302
303  /**
304   * Is the ultrasonic enabled.
305   *
306   * @return true if the ultrasonic is enabled
307   */
308  public boolean isEnabled() {
309    return m_enabled;
310  }
311
312  /**
313   * Set if the ultrasonic is enabled.
314   *
315   * @param enable set to true to enable the ultrasonic
316   */
317  public void setEnabled(boolean enable) {
318    m_enabled = enable;
319  }
320
321  @Override
322  public void initSendable(SendableBuilder builder) {
323    builder.setSmartDashboardType("Ultrasonic");
324    builder.addDoubleProperty("Value", this::getRangeInches, null);
325  }
326}