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.counter;
006
007import edu.wpi.first.hal.CounterJNI;
008import edu.wpi.first.hal.HAL;
009import edu.wpi.first.util.sendable.Sendable;
010import edu.wpi.first.util.sendable.SendableBuilder;
011import edu.wpi.first.util.sendable.SendableRegistry;
012
013/**
014 * Up Down Counter.
015 *
016 * <p>This class can count edges on a single digital input or count up based on an edge from one
017 * digital input and down on an edge from another digital input.
018 */
019public class UpDownCounter implements Sendable, AutoCloseable {
020  private final int m_handle;
021
022  /**
023   * Constructs a new UpDown Counter.
024   *
025   * @param channel The up count source (can be null).
026   * @param configuration The edge configuration.
027   */
028  @SuppressWarnings("this-escape")
029  public UpDownCounter(int channel, EdgeConfiguration configuration) {
030    m_handle = CounterJNI.initializeCounter(channel, configuration.rising);
031
032    reset();
033
034    HAL.reportUsage("IO", channel, "UpDownCounter");
035    SendableRegistry.add(this, "UpDown Counter", channel);
036  }
037
038  @Override
039  public void close() {
040    SendableRegistry.remove(this);
041    CounterJNI.freeCounter(m_handle);
042  }
043
044  /**
045   * Sets the configuration for the up source.
046   *
047   * @param configuration The up source configuration.
048   */
049  public void setEdgeConfiguration(EdgeConfiguration configuration) {
050    CounterJNI.setCounterEdgeConfiguration(m_handle, configuration.rising);
051  }
052
053  /** Resets the current count. */
054  public final void reset() {
055    CounterJNI.resetCounter(m_handle);
056  }
057
058  /**
059   * Gets the current count.
060   *
061   * @return The current count.
062   */
063  public int getCount() {
064    return CounterJNI.getCounter(m_handle);
065  }
066
067  @Override
068  public void initSendable(SendableBuilder builder) {
069    builder.setSmartDashboardType("UpDown Counter");
070    builder.addDoubleProperty("Count", this::getCount, null);
071  }
072}