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 edu.wpi.first.hal.DIOJNI;
008import edu.wpi.first.hal.HAL;
009import edu.wpi.first.hal.SimDevice;
010import edu.wpi.first.util.sendable.Sendable;
011import edu.wpi.first.util.sendable.SendableBuilder;
012import edu.wpi.first.util.sendable.SendableRegistry;
013
014/**
015 * Class to read a digital input. This class will read digital inputs and return the current value
016 * on the channel. Other devices such as encoders, gear tooth sensors, etc. that are implemented
017 * elsewhere will automatically allocate digital inputs and outputs as required. This class is only
018 * for devices like switches etc. that aren't implemented anywhere else.
019 */
020public class DigitalInput implements AutoCloseable, Sendable {
021  private final int m_channel;
022  private int m_handle;
023
024  /**
025   * Create an instance of a Digital Input class. Creates a digital input given a channel.
026   *
027   * @param channel the DIO channel for the digital input 0-9 are on-board, 10-25 are on the MXP
028   */
029  @SuppressWarnings("this-escape")
030  public DigitalInput(int channel) {
031    SensorUtil.checkDigitalChannel(channel);
032    m_channel = channel;
033
034    m_handle = DIOJNI.initializeDIOPort(channel, true);
035
036    HAL.reportUsage("IO", channel, "DigitalInput");
037    SendableRegistry.add(this, "DigitalInput", channel);
038  }
039
040  @Override
041  public void close() {
042    SendableRegistry.remove(this);
043    DIOJNI.freeDIOPort(m_handle);
044    m_handle = 0;
045  }
046
047  /**
048   * Get the value from a digital input channel. Retrieve the value of a single digital input
049   * channel from the FPGA.
050   *
051   * @return the status of the digital input
052   */
053  public boolean get() {
054    return DIOJNI.getDIO(m_handle);
055  }
056
057  /**
058   * Get the channel of the digital input.
059   *
060   * @return The GPIO channel number that this object represents.
061   */
062  public int getChannel() {
063    return m_channel;
064  }
065
066  /**
067   * Indicates this input is used by a simulated device.
068   *
069   * @param device simulated device handle
070   */
071  public void setSimDevice(SimDevice device) {
072    DIOJNI.setDIOSimDevice(m_handle, device.getNativeHandle());
073  }
074
075  @Override
076  public void initSendable(SendableBuilder builder) {
077    builder.setSmartDashboardType("Digital Input");
078    builder.addBooleanProperty("Value", this::get, null);
079  }
080}