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 org.wpilib.hardware.discrete;
006
007import org.wpilib.hardware.hal.DIOJNI;
008import org.wpilib.hardware.hal.HAL;
009import org.wpilib.hardware.hal.SimDevice;
010import org.wpilib.util.sendable.Sendable;
011import org.wpilib.util.sendable.SendableBuilder;
012import org.wpilib.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 SmartIO channel for the digital input
028   */
029  @SuppressWarnings("this-escape")
030  public DigitalInput(int channel) {
031    m_channel = channel;
032
033    m_handle = DIOJNI.initializeDIOPort(channel, true);
034
035    HAL.reportUsage("IO", channel, "DigitalInput");
036    SendableRegistry.add(this, "DigitalInput", channel);
037  }
038
039  @Override
040  public void close() {
041    SendableRegistry.remove(this);
042    DIOJNI.freeDIOPort(m_handle);
043    m_handle = 0;
044  }
045
046  /**
047   * Get the value from a digital input channel. Retrieve the value of a single digital input
048   * channel from the FPGA.
049   *
050   * @return the status of the digital input
051   */
052  public boolean get() {
053    return DIOJNI.getDIO(m_handle);
054  }
055
056  /**
057   * Get the channel of the digital input.
058   *
059   * @return The GPIO channel number that this object represents.
060   */
061  public int getChannel() {
062    return m_channel;
063  }
064
065  /**
066   * Indicates this input is used by a simulated device.
067   *
068   * @param device simulated device handle
069   */
070  public void setSimDevice(SimDevice device) {
071    DIOJNI.setDIOSimDevice(m_handle, device.getNativeHandle());
072  }
073
074  @Override
075  public void initSendable(SendableBuilder builder) {
076    builder.setSmartDashboardType("Digital Input");
077    builder.addBooleanProperty("Value", this::get, null);
078  }
079}