WPILib Reorganization

This is a major restructuring of the WPILib repository to simply build
procedures and remove the remnants of Maven from everything except the
eclipse plugins. Gradle files have been largely simplified or rewritten,
taking advantage of splitting up parts of the build into separate build
files for ease of reading.

The eclipse plugins are now in a separate project, as is ntcore. All
dependencies are resolved via Maven dependencies, with the
Jenkins-maintained WPILib repo. Project structures have also been
simplified: we no longer have separate subprojects inside wpilibc and
wpilibj. Where possible, these changes hav been done with git renames,
to make sure we still have full history for all repositories. Other
unrelated subprojects have also been broken out: OutlineViewer is now a
separate project.

Change-Id: Ib4e2a6e1a2f66427a14f16612b0e0d69ed661878
This commit is contained in:
Fredric Silberberg
2015-09-24 20:26:49 -04:00
parent c20d34c2b6
commit 6d854afb0e
1769 changed files with 2278 additions and 333177 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,20 @@
//
// This file is auto-generated by wpilibj/wpilibJavaJNI/nivision/gen_java.py
// Please do not edit!
//
package com.ni.vision;
public class VisionException extends RuntimeException {
private static final long serialVersionUID = 1L;
public VisionException(String msg) {
super(msg);
}
@Override
public String toString() {
return "VisionException [" + super.toString() + "]";
}
}

View File

@@ -0,0 +1,183 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import java.nio.ByteOrder;
import java.nio.ByteBuffer;
import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tInstances;
import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType;
import edu.wpi.first.wpilibj.communication.UsageReporting;
import edu.wpi.first.wpilibj.interfaces.Accelerometer;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable;
import edu.wpi.first.wpilibj.tables.ITable;
/**
*
* @author dtjones
*/
public class ADXL345_I2C extends SensorBase implements Accelerometer, LiveWindowSendable {
private static final byte kAddress = 0x1D;
private static final byte kPowerCtlRegister = 0x2D;
private static final byte kDataFormatRegister = 0x31;
private static final byte kDataRegister = 0x32;
private static final double kGsPerLSB = 0.00390625;
private static final byte kPowerCtl_Link = 0x20, kPowerCtl_AutoSleep = 0x10,
kPowerCtl_Measure = 0x08, kPowerCtl_Sleep = 0x04;
private static final byte kDataFormat_SelfTest = (byte) 0x80, kDataFormat_SPI = 0x40,
kDataFormat_IntInvert = 0x20, kDataFormat_FullRes = 0x08, kDataFormat_Justify = 0x04;
public static enum Axes {
kX((byte) 0x00),
kY((byte) 0x02),
kZ((byte) 0x04);
/**
* The integer value representing this enumeration
*/
public final byte value;
private Axes(byte value) {
this.value = value;
}
}
public static class AllAxes {
public double XAxis;
public double YAxis;
public double ZAxis;
}
private I2C m_i2c;
/**
* Constructor.
*$
* @param port The I2C port the accelerometer is attached to
* @param range The range (+ or -) that the accelerometer will measure.
*/
public ADXL345_I2C(I2C.Port port, Range range) {
m_i2c = new I2C(port, kAddress);
// Turn on the measurements
m_i2c.write(kPowerCtlRegister, kPowerCtl_Measure);
setRange(range);
UsageReporting.report(tResourceType.kResourceType_ADXL345, tInstances.kADXL345_I2C);
LiveWindow.addSensor("ADXL345_I2C", port.getValue(), this);
}
/** {inheritdoc} */
@Override
public void setRange(Range range) {
byte value = 0;
switch (range) {
case k2G:
value = 0;
break;
case k4G:
value = 1;
break;
case k8G:
value = 2;
break;
case k16G:
value = 3;
break;
}
// Specify the data format to read
m_i2c.write(kDataFormatRegister, kDataFormat_FullRes | value);
}
/** {@inheritDoc} */
@Override
public double getX() {
return getAcceleration(Axes.kX);
}
/** {@inheritDoc} */
@Override
public double getY() {
return getAcceleration(Axes.kY);
}
/** {@inheritDoc} */
@Override
public double getZ() {
return getAcceleration(Axes.kZ);
}
/**
* Get the acceleration of one axis in Gs.
*
* @param axis The axis to read from.
* @return Acceleration of the ADXL345 in Gs.
*/
public double getAcceleration(Axes axis) {
ByteBuffer rawAccel = ByteBuffer.allocateDirect(2);
m_i2c.read(kDataRegister + axis.value, 2, rawAccel);
// Sensor is little endian... swap bytes
rawAccel.order(ByteOrder.LITTLE_ENDIAN);
return rawAccel.getShort(0) * kGsPerLSB;
}
/**
* Get the acceleration of all axes in Gs.
*
* @return An object containing the acceleration measured on each axis of the
* ADXL345 in Gs.
*/
public AllAxes getAccelerations() {
AllAxes data = new AllAxes();
ByteBuffer rawData = ByteBuffer.allocateDirect(6);
m_i2c.read(kDataRegister, 6, rawData);
// Sensor is little endian... swap bytes
rawData.order(ByteOrder.LITTLE_ENDIAN);
data.XAxis = rawData.getShort(0) * kGsPerLSB;
data.YAxis = rawData.getShort(2) * kGsPerLSB;
data.ZAxis = rawData.getShort(4) * kGsPerLSB;
return data;
}
public String getSmartDashboardType() {
return "3AxisAccelerometer";
}
private ITable m_table;
/** {@inheritDoc} */
public void initTable(ITable subtable) {
m_table = subtable;
updateTable();
}
/** {@inheritDoc} */
public void updateTable() {
if (m_table != null) {
m_table.putNumber("X", getX());
m_table.putNumber("Y", getY());
m_table.putNumber("Z", getZ());
}
}
/** {@inheritDoc} */
public ITable getTable() {
return m_table;
}
public void startLiveWindowMode() {}
public void stopLiveWindowMode() {}
}

View File

@@ -0,0 +1,219 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import java.nio.ByteOrder;
import java.nio.ByteBuffer;
import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tInstances;
import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType;
import edu.wpi.first.wpilibj.communication.UsageReporting;
import edu.wpi.first.wpilibj.interfaces.Accelerometer;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable;
import edu.wpi.first.wpilibj.tables.ITable;
/**
*
* @author dtjones
* @author mwills
*/
public class ADXL345_SPI extends SensorBase implements Accelerometer, LiveWindowSendable {
private static final int kPowerCtlRegister = 0x2D;
private static final int kDataFormatRegister = 0x31;
private static final int kDataRegister = 0x32;
private static final double kGsPerLSB = 0.00390625;
private static final int kAddress_Read = 0x80;
private static final int kAddress_MultiByte = 0x40;
private static final int kPowerCtl_Link = 0x20;
private static final int kPowerCtl_AutoSleep = 0x10;
private static final int kPowerCtl_Measure = 0x08;
private static final int kPowerCtl_Sleep = 0x04;
private static final int kDataFormat_SelfTest = 0x80;
private static final int kDataFormat_SPI = 0x40;
private static final int kDataFormat_IntInvert = 0x20;
private static final int kDataFormat_FullRes = 0x08;
private static final int kDataFormat_Justify = 0x04;
public static enum Axes {
kX((byte) 0x00),
kY((byte) 0x02),
kZ((byte) 0x04);
/**
* The integer value representing this enumeration
*/
public final byte value;
private Axes(byte value) {
this.value = value;
}
}
public static class AllAxes {
public double XAxis;
public double YAxis;
public double ZAxis;
}
private SPI m_spi;
/**
* Constructor.
*
* @param port The SPI port that the accelerometer is connected to
* @param range The range (+ or -) that the accelerometer will measure.
*/
public ADXL345_SPI(SPI.Port port, Range range) {
m_spi = new SPI(port);
init(range);
LiveWindow.addSensor("ADXL345_SPI", port.getValue(), this);
}
public void free() {
m_spi.free();
}
/**
* Set SPI bus parameters, bring device out of sleep and set format
*
* @param range The range (+ or -) that the accelerometer will measure.
*/
private void init(Range range) {
m_spi.setClockRate(500000);
m_spi.setMSBFirst();
m_spi.setSampleDataOnFalling();
m_spi.setClockActiveLow();
m_spi.setChipSelectActiveHigh();
// Turn on the measurements
byte[] commands = new byte[2];
commands[0] = kPowerCtlRegister;
commands[1] = kPowerCtl_Measure;
m_spi.write(commands, 2);
setRange(range);
UsageReporting.report(tResourceType.kResourceType_ADXL345, tInstances.kADXL345_SPI);
}
/** {inheritdoc} */
@Override
public void setRange(Range range) {
byte value = 0;
switch (range) {
case k2G:
value = 0;
break;
case k4G:
value = 1;
break;
case k8G:
value = 2;
break;
case k16G:
value = 3;
break;
}
// Specify the data format to read
byte[] commands = new byte[] {kDataFormatRegister, (byte) (kDataFormat_FullRes | value)};
m_spi.write(commands, commands.length);
}
/** {@inheritDoc} */
@Override
public double getX() {
return getAcceleration(Axes.kX);
}
/** {@inheritDoc} */
@Override
public double getY() {
return getAcceleration(Axes.kY);
}
/** {@inheritDoc} */
@Override
public double getZ() {
return getAcceleration(Axes.kZ);
}
/**
* Get the acceleration of one axis in Gs.
*
* @param axis The axis to read from.
* @return Acceleration of the ADXL345 in Gs.
*/
public double getAcceleration(ADXL345_SPI.Axes axis) {
ByteBuffer transferBuffer = ByteBuffer.allocateDirect(3);
transferBuffer.put(0, (byte) ((kAddress_Read | kAddress_MultiByte | kDataRegister) + axis.value));
m_spi.transaction(transferBuffer, transferBuffer, 3);
// Sensor is little endian
transferBuffer.order(ByteOrder.LITTLE_ENDIAN);
return transferBuffer.getShort(1) * kGsPerLSB;
}
/**
* Get the acceleration of all axes in Gs.
*
* @return An object containing the acceleration measured on each axis of the
* ADXL345 in Gs.
*/
public ADXL345_SPI.AllAxes getAccelerations() {
ADXL345_SPI.AllAxes data = new ADXL345_SPI.AllAxes();
if (m_spi != null) {
ByteBuffer dataBuffer = ByteBuffer.allocateDirect(7);
// Select the data address.
dataBuffer.put(0, (byte) (kAddress_Read | kAddress_MultiByte | kDataRegister));
m_spi.transaction(dataBuffer, dataBuffer, 7);
// Sensor is little endian... swap bytes
dataBuffer.order(ByteOrder.LITTLE_ENDIAN);
data.XAxis = dataBuffer.getShort(1) * kGsPerLSB;
data.YAxis = dataBuffer.getShort(3) * kGsPerLSB;
data.ZAxis = dataBuffer.getShort(5) * kGsPerLSB;
}
return data;
}
public String getSmartDashboardType() {
return "3AxisAccelerometer";
}
private ITable m_table;
/** {@inheritDoc} */
public void initTable(ITable subtable) {
m_table = subtable;
updateTable();
}
/** {@inheritDoc} */
public void updateTable() {
if (m_table != null) {
m_table.putNumber("X", getX());
m_table.putNumber("Y", getY());
m_table.putNumber("Z", getZ());
}
}
/** {@inheritDoc} */
public ITable getTable() {
return m_table;
}
public void startLiveWindowMode() {}
public void stopLiveWindowMode() {}
}

View File

@@ -0,0 +1,25 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
/**
* Structure for holding the values stored in an accumulator
*$
* @author brad
*/
public class AccumulatorResult {
/**
* The total value accumulated
*/
public long value;
/**
* The number of sample vaule was accumulated over
*/
public long count;
}

View File

@@ -0,0 +1,183 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType;
import edu.wpi.first.wpilibj.communication.UsageReporting;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable;
import edu.wpi.first.wpilibj.tables.ITable;
/**
* Handle operation of an analog accelerometer. The accelerometer reads
* acceleration directly through the sensor. Many sensors have multiple axis and
* can be treated as multiple devices. Each is calibrated by finding the center
* value over a period of time.
*/
public class AnalogAccelerometer extends SensorBase implements PIDSource, LiveWindowSendable {
private AnalogInput m_analogChannel;
private double m_voltsPerG = 1.0;
private double m_zeroGVoltage = 2.5;
private boolean m_allocatedChannel;
protected PIDSourceType m_pidSource = PIDSourceType.kDisplacement;
/**
* Common initialization
*/
private void initAccelerometer() {
UsageReporting.report(tResourceType.kResourceType_Accelerometer, m_analogChannel.getChannel());
LiveWindow.addSensor("Accelerometer", m_analogChannel.getChannel(), this);
}
/**
* Create a new instance of an accelerometer.
*
* The constructor allocates desired analog channel.
*$
* @param channel The channel number for the analog input the accelerometer is
* connected to
*/
public AnalogAccelerometer(final int channel) {
m_allocatedChannel = true;
m_analogChannel = new AnalogInput(channel);
initAccelerometer();
}
/**
* Create a new instance of Accelerometer from an existing AnalogChannel. Make
* a new instance of accelerometer given an AnalogChannel. This is
* particularly useful if the port is going to be read as an analog channel as
* well as through the Accelerometer class.
*$
* @param channel The existing AnalogInput object for the analog input the
* accelerometer is connected to
*/
public AnalogAccelerometer(AnalogInput channel) {
m_allocatedChannel = false;
if (channel == null)
throw new NullPointerException("Analog Channel given was null");
m_analogChannel = channel;
initAccelerometer();
}
/**
* Delete the analog components used for the accelerometer.
*/
public void free() {
if (m_analogChannel != null && m_allocatedChannel) {
m_analogChannel.free();
}
m_analogChannel = null;
}
/**
* Return the acceleration in Gs.
*
* The acceleration is returned units of Gs.
*
* @return The current acceleration of the sensor in Gs.
*/
public double getAcceleration() {
return (m_analogChannel.getAverageVoltage() - m_zeroGVoltage) / m_voltsPerG;
}
/**
* Set the accelerometer sensitivity.
*
* This sets the sensitivity of the accelerometer used for calculating the
* acceleration. The sensitivity varies by accelerometer model. There are
* constants defined for various models.
*
* @param sensitivity The sensitivity of accelerometer in Volts per G.
*/
public void setSensitivity(double sensitivity) {
m_voltsPerG = sensitivity;
}
/**
* Set the voltage that corresponds to 0 G.
*
* The zero G voltage varies by accelerometer model. There are constants
* defined for various models.
*
* @param zero The zero G voltage.
*/
public void setZero(double zero) {
m_zeroGVoltage = zero;
}
/**
* {@inheritDoc}
*/
public void setPIDSourceType(PIDSourceType pidSource) {
m_pidSource = pidSource;
}
/**
* {@inheritDoc}
*/
public PIDSourceType getPIDSourceType() {
return m_pidSource;
}
/**
* Get the Acceleration for the PID Source parent.
*
* @return The current acceleration in Gs.
*/
public double pidGet() {
return getAcceleration();
}
public String getSmartDashboardType() {
return "Accelerometer";
}
/*
* Live Window code, only does anything if live window is activated.
*/
private ITable m_table;
/**
* {@inheritDoc}
*/
public void initTable(ITable subtable) {
m_table = subtable;
updateTable();
}
/**
* {@inheritDoc}
*/
public ITable getTable() {
return m_table;
}
/**
* {@inheritDoc}
*/
public void updateTable() {
if (m_table != null) {
m_table.putNumber("Value", getAcceleration());
}
}
/**
* Analog Channels don't have to do anything special when entering the
* LiveWindow. {@inheritDoc}
*/
public void startLiveWindowMode() {}
/**
* Analog Channels don't have to do anything special when exiting the
* LiveWindow. {@inheritDoc}
*/
public void stopLiveWindowMode() {}
}

View File

@@ -0,0 +1,189 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType;
import edu.wpi.first.wpilibj.communication.UsageReporting;
import edu.wpi.first.wpilibj.interfaces.Gyro;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable;
import edu.wpi.first.wpilibj.tables.ITable;
/**
* Use a rate gyro to return the robots heading relative to a starting position.
* The Gyro class tracks the robots heading based on the starting position. As
* the robot rotates the new heading is computed by integrating the rate of
* rotation returned by the sensor. When the class is instantiated, it does a
* short calibration routine where it samples the gyro while at rest to
* determine the default offset. This is subtracted from each sample to
* determine the heading.
*
* This class is for gyro sensors that connect to an analog input.
*/
public class AnalogGyro extends GyroBase implements Gyro, PIDSource, LiveWindowSendable {
static final int kOversampleBits = 10;
static final int kAverageBits = 0;
static final double kSamplesPerSecond = 50.0;
static final double kCalibrationSampleTime = 5.0;
static final double kDefaultVoltsPerDegreePerSecond = 0.007;
protected AnalogInput m_analog;
double m_voltsPerDegreePerSecond;
double m_offset;
int m_center;
boolean m_channelAllocated = false;
AccumulatorResult result;
private PIDSourceType m_pidSource;
/**
* {@inheritDoc}
*/
public void initGyro() {
result = new AccumulatorResult();
if (m_analog == null) {
System.out.println("Null m_analog");
}
m_voltsPerDegreePerSecond = kDefaultVoltsPerDegreePerSecond;
m_analog.setAverageBits(kAverageBits);
m_analog.setOversampleBits(kOversampleBits);
double sampleRate = kSamplesPerSecond * (1 << (kAverageBits + kOversampleBits));
AnalogInput.setGlobalSampleRate(sampleRate);
Timer.delay(1.0);
m_analog.initAccumulator();
m_analog.resetAccumulator();
Timer.delay(kCalibrationSampleTime);
m_analog.getAccumulatorOutput(result);
m_center = (int) ((double) result.value / (double) result.count + .5);
m_offset = ((double) result.value / (double) result.count) - m_center;
m_analog.setAccumulatorCenter(m_center);
m_analog.resetAccumulator();
setDeadband(0.0);
setPIDSourceType(PIDSourceType.kDisplacement);
UsageReporting.report(tResourceType.kResourceType_Gyro, m_analog.getChannel());
LiveWindow.addSensor("AnalogGyro", m_analog.getChannel(), this);
}
/**
* Gyro constructor using the channel number
*
* @param channel The analog channel the gyro is connected to. Gyros can only
* be used on on-board channels 0-1.
*/
public AnalogGyro(int channel) {
this(new AnalogInput(channel));
m_channelAllocated = true;
}
/**
* Gyro constructor with a precreated analog channel object. Use this
* constructor when the analog channel needs to be shared.
*
* @param channel The AnalogInput object that the gyro is connected to. Gyros
* can only be used on on-board channels 0-1.
*/
public AnalogGyro(AnalogInput channel) {
m_analog = channel;
if (m_analog == null) {
throw new NullPointerException("AnalogInput supplied to Gyro constructor is null");
}
initGyro();
}
/**
* {@inheritDoc}
*/
public void reset() {
if (m_analog != null) {
m_analog.resetAccumulator();
}
}
/**
* Delete (free) the accumulator and the analog components used for the gyro.
*/
@Override
public void free() {
if (m_analog != null && m_channelAllocated) {
m_analog.free();
}
m_analog = null;
}
/**
* {@inheritDoc}
*/
public double getAngle() {
if (m_analog == null) {
return 0.0;
} else {
m_analog.getAccumulatorOutput(result);
long value = result.value - (long) (result.count * m_offset);
double scaledValue =
value * 1e-9 * m_analog.getLSBWeight() * (1 << m_analog.getAverageBits())
/ (AnalogInput.getGlobalSampleRate() * m_voltsPerDegreePerSecond);
return scaledValue;
}
}
/**
* {@inheritDoc}
*/
public double getRate() {
if (m_analog == null) {
return 0.0;
} else {
return (m_analog.getAverageValue() - (m_center + m_offset)) * 1e-9 * m_analog.getLSBWeight()
/ ((1 << m_analog.getOversampleBits()) * m_voltsPerDegreePerSecond);
}
}
/**
* Set the gyro sensitivity. This takes the number of volts/degree/second
* sensitivity of the gyro and uses it in subsequent calculations to allow the
* code to work with multiple gyros. This value is typically found in the gyro
* datasheet.
*
* @param voltsPerDegreePerSecond The sensitivity in Volts/degree/second.
*/
public void setSensitivity(double voltsPerDegreePerSecond) {
m_voltsPerDegreePerSecond = voltsPerDegreePerSecond;
}
/**
* Set the size of the neutral zone. Any voltage from the gyro less than this
* amount from the center is considered stationary. Setting a deadband will
* decrease the amount of drift when the gyro isn't rotating, but will make it
* less accurate.
*
* @param volts The size of the deadband in volts
*/
void setDeadband(double volts) {
int deadband =
(int) (volts * 1e9 / m_analog.getLSBWeight() * (1 << m_analog.getOversampleBits()));
m_analog.setAccumulatorDeadband(deadband);
}
/*
* Live Window code, only does anything if live window is activated.
*/
@Override
public String getSmartDashboardType() {
return "AnalogGyro";
}
}

View File

@@ -0,0 +1,435 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
import java.nio.LongBuffer;
import java.nio.ByteBuffer;
// import com.sun.jna.Pointer;
import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType;
import edu.wpi.first.wpilibj.communication.UsageReporting;
import edu.wpi.first.wpilibj.hal.AnalogJNI;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable;
import edu.wpi.first.wpilibj.tables.ITable;
import edu.wpi.first.wpilibj.util.AllocationException;
import edu.wpi.first.wpilibj.util.CheckedAllocationException;
/**
* Analog channel class.
*
* Each analog channel is read from hardware as a 12-bit number representing 0V
* to 5V.
*
* Connected to each analog channel is an averaging and oversampling engine.
* This engine accumulates the specified ( by setAverageBits() and
* setOversampleBits() ) number of samples before returning a new value. This is
* not a sliding window average. The only difference between the oversampled
* samples and the averaged samples is that the oversampled samples are simply
* accumulated effectively increasing the resolution, while the averaged samples
* are divided by the number of samples to retain the resolution, but get more
* stable values.
*/
public class AnalogInput extends SensorBase implements PIDSource, LiveWindowSendable {
private static final int kAccumulatorSlot = 1;
private static Resource channels = new Resource(kAnalogInputChannels);
private long m_port;
private int m_channel;
private static final int[] kAccumulatorChannels = {0, 1};
private long m_accumulatorOffset;
protected PIDSourceType m_pidSource = PIDSourceType.kDisplacement;
/**
* Construct an analog channel.
*
* @param channel The channel number to represent. 0-3 are on-board 4-7 are on
* the MXP port.
*/
public AnalogInput(final int channel) {
m_channel = channel;
if (!AnalogJNI.checkAnalogInputChannel(channel)) {
throw new AllocationException("Analog input channel " + m_channel
+ " cannot be allocated. Channel is not present.");
}
try {
channels.allocate(channel);
} catch (CheckedAllocationException e) {
throw new AllocationException("Analog input channel " + m_channel + " is already allocated");
}
long port_pointer = AnalogJNI.getPort((byte) channel);
m_port = AnalogJNI.initializeAnalogInputPort(port_pointer);
LiveWindow.addSensor("AnalogInput", channel, this);
UsageReporting.report(tResourceType.kResourceType_AnalogChannel, channel);
}
/**
* Channel destructor.
*/
public void free() {
channels.free(m_channel);
m_channel = 0;
m_accumulatorOffset = 0;
}
/**
* Get a sample straight from this channel. The sample is a 12-bit value
* representing the 0V to 5V range of the A/D converter. The units are in A/D
* converter codes. Use GetVoltage() to get the analog value in calibrated
* units.
*
* @return A sample straight from this channel.
*/
public int getValue() {
return AnalogJNI.getAnalogValue(m_port);
}
/**
* Get a sample from the output of the oversample and average engine for this
* channel. The sample is 12-bit + the bits configured in SetOversampleBits().
* The value configured in setAverageBits() will cause this value to be
* averaged 2^bits number of samples. This is not a sliding window. The sample
* will not change until 2^(OversampleBits + AverageBits) samples have been
* acquired from this channel. Use getAverageVoltage() to get the analog value
* in calibrated units.
*
* @return A sample from the oversample and average engine for this channel.
*/
public int getAverageValue() {
return AnalogJNI.getAnalogAverageValue(m_port);
}
/**
* Get a scaled sample straight from this channel. The value is scaled to
* units of Volts using the calibrated scaling data from getLSBWeight() and
* getOffset().
*
* @return A scaled sample straight from this channel.
*/
public double getVoltage() {
return AnalogJNI.getAnalogVoltage(m_port);
}
/**
* Get a scaled sample from the output of the oversample and average engine
* for this channel. The value is scaled to units of Volts using the
* calibrated scaling data from getLSBWeight() and getOffset(). Using
* oversampling will cause this value to be higher resolution, but it will
* update more slowly. Using averaging will cause this value to be more
* stable, but it will update more slowly.
*
* @return A scaled sample from the output of the oversample and average
* engine for this channel.
*/
public double getAverageVoltage() {
return AnalogJNI.getAnalogAverageVoltage(m_port);
}
/**
* Get the factory scaling least significant bit weight constant. The least
* significant bit weight constant for the channel that was calibrated in
* manufacturing and stored in an eeprom.
*
* Volts = ((LSB_Weight * 1e-9) * raw) - (Offset * 1e-9)
*
* @return Least significant bit weight.
*/
public long getLSBWeight() {
return AnalogJNI.getAnalogLSBWeight(m_port);
}
/**
* Get the factory scaling offset constant. The offset constant for the
* channel that was calibrated in manufacturing and stored in an eeprom.
*
* Volts = ((LSB_Weight * 1e-9) * raw) - (Offset * 1e-9)
*
* @return Offset constant.
*/
public int getOffset() {
return AnalogJNI.getAnalogOffset(m_port);
}
/**
* Get the channel number.
*
* @return The channel number.
*/
public int getChannel() {
return m_channel;
}
/**
* Set the number of averaging bits. This sets the number of averaging bits.
* The actual number of averaged samples is 2^bits. The averaging is done
* automatically in the FPGA.
*
* @param bits The number of averaging bits.
*/
public void setAverageBits(final int bits) {
AnalogJNI.setAnalogAverageBits(m_port, bits);
}
/**
* Get the number of averaging bits. This gets the number of averaging bits
* from the FPGA. The actual number of averaged samples is 2^bits. The
* averaging is done automatically in the FPGA.
*
* @return The number of averaging bits.
*/
public int getAverageBits() {
return AnalogJNI.getAnalogAverageBits(m_port);
}
/**
* Set the number of oversample bits. This sets the number of oversample bits.
* The actual number of oversampled values is 2^bits. The oversampling is done
* automatically in the FPGA.
*
* @param bits The number of oversample bits.
*/
public void setOversampleBits(final int bits) {
AnalogJNI.setAnalogOversampleBits(m_port, bits);
}
/**
* Get the number of oversample bits. This gets the number of oversample bits
* from the FPGA. The actual number of oversampled values is 2^bits. The
* oversampling is done automatically in the FPGA.
*
* @return The number of oversample bits.
*/
public int getOversampleBits() {
return AnalogJNI.getAnalogOversampleBits(m_port);
}
/**
* Initialize the accumulator.
*/
public void initAccumulator() {
if (!isAccumulatorChannel()) {
throw new AllocationException("Accumulators are only available on slot " + kAccumulatorSlot
+ " on channels " + kAccumulatorChannels[0] + "," + kAccumulatorChannels[1]);
}
m_accumulatorOffset = 0;
AnalogJNI.initAccumulator(m_port);
}
/**
* Set an initial value for the accumulator.
*
* This will be added to all values returned to the user.
*
* @param initialValue The value that the accumulator should start from when
* reset.
*/
public void setAccumulatorInitialValue(long initialValue) {
m_accumulatorOffset = initialValue;
}
/**
* Resets the accumulator to the initial value.
*/
public void resetAccumulator() {
AnalogJNI.resetAccumulator(m_port);
// Wait until the next sample, so the next call to getAccumulator*()
// won't have old values.
final double sampleTime = 1.0 / getGlobalSampleRate();
final double overSamples = 1 << getOversampleBits();
final double averageSamples = 1 << getAverageBits();
Timer.delay(sampleTime * overSamples * averageSamples);
}
/**
* Set the center value of the accumulator.
*
* The center value is subtracted from each A/D value before it is added to
* the accumulator. This is used for the center value of devices like gyros
* and accelerometers to take the device offset into account when integrating.
*
* This center value is based on the output of the oversampled and averaged
* source the accumulator channel. Because of this, any non-zero oversample
* bits will affect the size of the value for this field.
*/
public void setAccumulatorCenter(int center) {
AnalogJNI.setAccumulatorCenter(m_port, center);
}
/**
* Set the accumulator's deadband.
*$
* @param deadband The deadband size in ADC codes (12-bit value)
*/
public void setAccumulatorDeadband(int deadband) {
AnalogJNI.setAccumulatorDeadband(m_port, deadband);
}
/**
* Read the accumulated value.
*
* Read the value that has been accumulating. The accumulator is attached
* after the oversample and average engine.
*
* @return The 64-bit value accumulated since the last Reset().
*/
public long getAccumulatorValue() {
return AnalogJNI.getAccumulatorValue(m_port) + m_accumulatorOffset;
}
/**
* Read the number of accumulated values.
*
* Read the count of the accumulated values since the accumulator was last
* Reset().
*
* @return The number of times samples from the channel were accumulated.
*/
public long getAccumulatorCount() {
return AnalogJNI.getAccumulatorCount(m_port);
}
/**
* Read the accumulated value and the number of accumulated values atomically.
*
* This function reads the value and count from the FPGA atomically. This can
* be used for averaging.
*
* @param result AccumulatorResult object to store the results in.
*/
public void getAccumulatorOutput(AccumulatorResult result) {
if (result == null) {
throw new IllegalArgumentException("Null parameter `result'");
}
if (!isAccumulatorChannel()) {
throw new IllegalArgumentException("Channel " + m_channel + " is not an accumulator channel.");
}
ByteBuffer value = ByteBuffer.allocateDirect(8);
// set the byte order
value.order(ByteOrder.LITTLE_ENDIAN);
ByteBuffer count = ByteBuffer.allocateDirect(4);
// set the byte order
count.order(ByteOrder.LITTLE_ENDIAN);
AnalogJNI.getAccumulatorOutput(m_port, value.asLongBuffer(), count.asIntBuffer());
result.value = value.asLongBuffer().get(0) + m_accumulatorOffset;
result.count = count.asIntBuffer().get(0);
}
/**
* Is the channel attached to an accumulator.
*
* @return The analog channel is attached to an accumulator.
*/
public boolean isAccumulatorChannel() {
for (int i = 0; i < kAccumulatorChannels.length; i++) {
if (m_channel == kAccumulatorChannels[i]) {
return true;
}
}
return false;
}
/**
* Set the sample rate per channel.
*
* This is a global setting for all channels. The maximum rate is 500kS/s
* divided by the number of channels in use. This is 62500 samples/s per
* channel if all 8 channels are used.
*$
* @param samplesPerSecond The number of samples per second.
*/
public static void setGlobalSampleRate(final double samplesPerSecond) {
AnalogJNI.setAnalogSampleRate((float) samplesPerSecond);
}
/**
* Get the current sample rate.
*
* This assumes one entry in the scan list. This is a global setting for all
* channels.
*
* @return Sample rate.
*/
public static double getGlobalSampleRate() {
return AnalogJNI.getAnalogSampleRate();
}
/**
* {@inheritDoc}
*/
public void setPIDSourceType(PIDSourceType pidSource) {
m_pidSource = pidSource;
}
/**
* {@inheritDoc}
*/
public PIDSourceType getPIDSourceType() {
return m_pidSource;
}
/**
* Get the average voltage for use with PIDController
*
* @return the average voltage
*/
public double pidGet() {
return getAverageVoltage();
}
/**
* Live Window code, only does anything if live window is activated.
*/
public String getSmartDashboardType() {
return "Analog Input";
}
private ITable m_table;
/**
* {@inheritDoc}
*/
public void initTable(ITable subtable) {
m_table = subtable;
updateTable();
}
/**
* {@inheritDoc}
*/
public void updateTable() {
if (m_table != null) {
m_table.putNumber("Value", getAverageVoltage());
}
}
/**
* {@inheritDoc}
*/
public ITable getTable() {
return m_table;
}
/**
* Analog Channels don't have to do anything special when entering the
* LiveWindow. {@inheritDoc}
*/
public void startLiveWindowMode() {}
/**
* Analog Channels don't have to do anything special when exiting the
* LiveWindow. {@inheritDoc}
*/
public void stopLiveWindowMode() {}
}

View File

@@ -0,0 +1,111 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2014. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType;
import edu.wpi.first.wpilibj.communication.UsageReporting;
import edu.wpi.first.wpilibj.hal.AnalogJNI;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable;
import edu.wpi.first.wpilibj.tables.ITable;
import edu.wpi.first.wpilibj.util.AllocationException;
import edu.wpi.first.wpilibj.util.CheckedAllocationException;
/**
* Analog output class.
*/
public class AnalogOutput extends SensorBase implements LiveWindowSendable {
private static Resource channels = new Resource(kAnalogOutputChannels);
private long m_port;
private int m_channel;
/**
* Construct an analog output on a specified MXP channel.
*
* @param channel The channel number to represent.
*/
public AnalogOutput(final int channel) {
m_channel = channel;
if (!AnalogJNI.checkAnalogOutputChannel(channel)) {
throw new AllocationException("Analog output channel " + m_channel
+ " cannot be allocated. Channel is not present.");
}
try {
channels.allocate(channel);
} catch (CheckedAllocationException e) {
throw new AllocationException("Analog output channel " + m_channel + " is already allocated");
}
long port_pointer = AnalogJNI.getPort((byte) channel);
m_port = AnalogJNI.initializeAnalogOutputPort(port_pointer);
LiveWindow.addSensor("AnalogOutput", channel, this);
UsageReporting.report(tResourceType.kResourceType_AnalogOutput, channel);
}
/**
* Channel destructor.
*/
public void free() {
channels.free(m_channel);
m_channel = 0;
}
public void setVoltage(double voltage) {
AnalogJNI.setAnalogOutput(m_port, voltage);
}
public double getVoltage() {
return AnalogJNI.getAnalogOutput(m_port);
}
/*
* Live Window code, only does anything if live window is activated.
*/
public String getSmartDashboardType() {
return "Analog Output";
}
private ITable m_table;
/**
* {@inheritDoc}
*/
public void initTable(ITable subtable) {
m_table = subtable;
updateTable();
}
/**
* {@inheritDoc}
*/
public void updateTable() {
if (m_table != null) {
m_table.putNumber("Value", getVoltage());
}
}
/**
* {@inheritDoc}
*/
public ITable getTable() {
return m_table;
}
/**
* Analog Channels don't have to do anything special when entering the
* LiveWindow. {@inheritDoc}
*/
public void startLiveWindowMode() {}
/**
* Analog Channels don't have to do anything special when exiting the
* LiveWindow. {@inheritDoc}
*/
public void stopLiveWindowMode() {}
}

View File

@@ -0,0 +1,235 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import edu.wpi.first.wpilibj.hal.HALUtil;
import edu.wpi.first.wpilibj.hal.PowerJNI;
import edu.wpi.first.wpilibj.interfaces.Potentiometer;
import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable;
import edu.wpi.first.wpilibj.tables.ITable;
/**
* Class for reading analog potentiometers. Analog potentiometers read in an
* analog voltage that corresponds to a position. The position is in whichever
* units you choose, by way of the scaling and offset constants passed to the
* constructor.
*
* @author Alex Henning
* @author Colby Skeggs (rail voltage)
*/
public class AnalogPotentiometer implements Potentiometer, LiveWindowSendable {
private double m_fullRange, m_offset;
private AnalogInput m_analog_input;
private boolean m_init_analog_input;
protected PIDSourceType m_pidSource = PIDSourceType.kDisplacement;
/**
* Common initialization code called by all constructors.
*$
* @param input The {@link AnalogInput} this potentiometer is plugged into.
* @param fullRange The scaling to multiply the voltage by to get a meaningful
* unit.
* @param offset The offset to add to the scaled value for controlling the
* zero value
*/
private void initPot(final AnalogInput input, double fullRange, double offset) {
this.m_fullRange = fullRange;
this.m_offset = offset;
m_analog_input = input;
}
/**
* AnalogPotentiometer constructor.
*
* Use the fullRange and offset values so that the output produces meaningful
* values. I.E: you have a 270 degree potentiometer and you want the output to
* be degrees with the halfway point as 0 degrees. The fullRange value is
* 270.0(degrees) and the offset is -135.0 since the halfway point after
* scaling is 135 degrees.
*$
* This will calculate the result from the fullRange times the fraction of the
* supply voltage, plus the offset.
*
* @param channel The analog channel this potentiometer is plugged into.
* @param fullRange The scaling to multiply the fraction by to get a
* meaningful unit.
* @param offset The offset to add to the scaled value for controlling the
* zero value
*/
public AnalogPotentiometer(final int channel, double fullRange, double offset) {
AnalogInput input = new AnalogInput(channel);
m_init_analog_input = true;
initPot(input, fullRange, offset);
}
/**
* AnalogPotentiometer constructor.
*
* Use the fullRange and offset values so that the output produces meaningful
* values. I.E: you have a 270 degree potentiometer and you want the output to
* be degrees with the halfway point as 0 degrees. The fullRange value is
* 270.0(degrees) and the offset is -135.0 since the halfway point after
* scaling is 135 degrees.
*$
* This will calculate the result from the fullRange times the fraction of the
* supply voltage, plus the offset.
*
* @param input The {@link AnalogInput} this potentiometer is plugged into.
* @param fullRange The scaling to multiply the fraction by to get a
* meaningful unit.
* @param offset The offset to add to the scaled value for controlling the
* zero value
*/
public AnalogPotentiometer(final AnalogInput input, double fullRange, double offset) {
m_init_analog_input = false;
initPot(input, fullRange, offset);
}
/**
* AnalogPotentiometer constructor.
*
* Use the fullRange and offset values so that the output produces meaningful
* values. I.E: you have a 270 degree potentiometer and you want the output to
* be degrees with the halfway point as 0 degrees. The fullRange value is
* 270.0(degrees) and the offset is -135.0 since the halfway point after
* scaling is 135 degrees.
*
* @param channel The analog channel this potentiometer is plugged into.
* @param scale The scaling to multiply the voltage by to get a meaningful
* unit.
*/
public AnalogPotentiometer(final int channel, double scale) {
this(channel, scale, 0);
}
/**
* AnalogPotentiometer constructor.
*
* Use the fullRange and offset values so that the output produces meaningful
* values. I.E: you have a 270 degree potentiometer and you want the output to
* be degrees with the halfway point as 0 degrees. The fullRange value is
* 270.0(degrees) and the offset is -135.0 since the halfway point after
* scaling is 135 degrees.
*
* @param input The {@link AnalogInput} this potentiometer is plugged into.
* @param scale The scaling to multiply the voltage by to get a meaningful
* unit.
*/
public AnalogPotentiometer(final AnalogInput input, double scale) {
this(input, scale, 0);
}
/**
* AnalogPotentiometer constructor.
*
* @param channel The analog channel this potentiometer is plugged into.
*/
public AnalogPotentiometer(final int channel) {
this(channel, 1, 0);
}
/**
* AnalogPotentiometer constructor.
*
* @param input The {@link AnalogInput} this potentiometer is plugged into.
*/
public AnalogPotentiometer(final AnalogInput input) {
this(input, 1, 0);
}
/**
* Get the current reading of the potentiometer.
*
* @return The current position of the potentiometer.
*/
public double get() {
return (m_analog_input.getVoltage() / ControllerPower.getVoltage5V()) * m_fullRange + m_offset;
}
/**
* {@inheritDoc}
*/
public void setPIDSourceType(PIDSourceType pidSource) {
if (!pidSource.equals(PIDSourceType.kDisplacement)) {
throw new IllegalArgumentException("Only displacement PID is allowed for potentiometers.");
}
m_pidSource = pidSource;
}
/**
* {@inheritDoc}
*/
public PIDSourceType getPIDSourceType() {
return m_pidSource;
}
/**
* Implement the PIDSource interface.
*
* @return The current reading.
*/
public double pidGet() {
return get();
}
/**
* Live Window code, only does anything if live window is activated.
*/
public String getSmartDashboardType() {
return "Analog Input";
}
private ITable m_table;
/**
* {@inheritDoc}
*/
public void initTable(ITable subtable) {
m_table = subtable;
updateTable();
}
/**
* {@inheritDoc}
*/
public void updateTable() {
if (m_table != null) {
m_table.putNumber("Value", get());
}
}
/**
* {@inheritDoc}
*/
public ITable getTable() {
return m_table;
}
public void free() {
if (m_init_analog_input) {
m_analog_input.free();
m_analog_input = null;
m_init_analog_input = false;
}
}
/**
* Analog Channels don't have to do anything special when entering the
* LiveWindow. {@inheritDoc}
*/
public void startLiveWindowMode() {}
/**
* Analog Channels don't have to do anything special when exiting the
* LiveWindow. {@inheritDoc}
*/
public void stopLiveWindowMode() {}
}

View File

@@ -0,0 +1,194 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import edu.wpi.first.wpilibj.AnalogTriggerOutput.AnalogTriggerType;
import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType;
import edu.wpi.first.wpilibj.communication.UsageReporting;
import edu.wpi.first.wpilibj.hal.AnalogJNI;
import edu.wpi.first.wpilibj.util.BoundaryException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
// import com.sun.jna.Pointer;
/**
* Class for creating and configuring Analog Triggers
*
* @author dtjones
*/
public class AnalogTrigger {
/**
* Exceptions dealing with improper operation of the Analog trigger
*/
public class AnalogTriggerException extends RuntimeException {
/**
* Create a new exception with the given message
*
* @param message the message to pass with the exception
*/
public AnalogTriggerException(String message) {
super(message);
}
}
/**
* Where the analog trigger is attached
*/
protected long m_port;
protected int m_index;
/**
* Initialize an analog trigger from a channel.
*
* @param channel the port to use for the analog trigger
*/
protected void initTrigger(final int channel) {
long port_pointer = AnalogJNI.getPort((byte) channel);
ByteBuffer index = ByteBuffer.allocateDirect(4);
index.order(ByteOrder.LITTLE_ENDIAN);
m_port =
AnalogJNI.initializeAnalogTrigger(port_pointer, index.asIntBuffer());
m_index = index.asIntBuffer().get(0);
UsageReporting.report(tResourceType.kResourceType_AnalogTrigger, channel);
}
/**
* Constructor for an analog trigger given a channel number.
*
* @param channel the port to use for the analog trigger 0-3 are on-board, 4-7
* are on the MXP port
*/
public AnalogTrigger(final int channel) {
initTrigger(channel);
}
/**
* Construct an analog trigger given an analog channel. This should be used in
* the case of sharing an analog channel between the trigger and an analog
* input object.
*
* @param channel the AnalogInput to use for the analog trigger
*/
public AnalogTrigger(AnalogInput channel) {
if (channel == null) {
throw new NullPointerException("The Analog Input given was null");
}
initTrigger(channel.getChannel());
}
/**
* Release the resources used by this object
*/
public void free() {
AnalogJNI.cleanAnalogTrigger(m_port);
m_port = 0;
}
/**
* Set the upper and lower limits of the analog trigger. The limits are given
* in ADC codes. If oversampling is used, the units must be scaled
* appropriately.
*
* @param lower the lower raw limit
* @param upper the upper raw limit
*/
public void setLimitsRaw(final int lower, final int upper) {
if (lower > upper) {
throw new BoundaryException("Lower bound is greater than upper");
}
AnalogJNI.setAnalogTriggerLimitsRaw(m_port, lower, upper);
}
/**
* Set the upper and lower limits of the analog trigger. The limits are given
* as floating point voltage values.
*
* @param lower the lower voltage limit
* @param upper the upper voltage limit
*/
public void setLimitsVoltage(double lower, double upper) {
if (lower > upper) {
throw new BoundaryException("Lower bound is greater than upper bound");
}
AnalogJNI.setAnalogTriggerLimitsVoltage(m_port, lower, upper);
}
/**
* Configure the analog trigger to use the averaged vs. raw values. If the
* value is true, then the averaged value is selected for the analog trigger,
* otherwise the immediate value is used.
*
* @param useAveragedValue true to use an averaged value, false otherwise
*/
public void setAveraged(boolean useAveragedValue) {
AnalogJNI.setAnalogTriggerAveraged(m_port, useAveragedValue);
}
/**
* Configure the analog trigger to use a filtered value. The analog trigger
* will operate with a 3 point average rejection filter. This is designed to
* help with 360 degree pot applications for the period where the pot crosses
* through zero.
*
* @param useFilteredValue true to use a filterd value, false otherwise
*/
public void setFiltered(boolean useFilteredValue) {
AnalogJNI.setAnalogTriggerFiltered(m_port, useFilteredValue);
}
/**
* Return the index of the analog trigger. This is the FPGA index of this
* analog trigger instance.
*
* @return The index of the analog trigger.
*/
public int getIndex() {
return m_index;
}
/**
* Return the InWindow output of the analog trigger. True if the analog input
* is between the upper and lower limits.
*
* @return The InWindow output of the analog trigger.
*/
public boolean getInWindow() {
return AnalogJNI.getAnalogTriggerInWindow(m_port);
}
/**
* Return the TriggerState output of the analog trigger. True if above upper
* limit. False if below lower limit. If in Hysteresis, maintain previous
* state.
*
* @return The TriggerState output of the analog trigger.
*/
public boolean getTriggerState() {
return AnalogJNI.getAnalogTriggerTriggerState(m_port);
}
/**
* Creates an AnalogTriggerOutput object. Gets an output object that can be
* used for routing. Caller is responsible for deleting the
* AnalogTriggerOutput object.
*
* @param type An enum of the type of output object to create.
* @return A pointer to a new AnalogTriggerOutput object.
*/
public AnalogTriggerOutput createOutput(AnalogTriggerType type) {
return new AnalogTriggerOutput(this, type);
}
}

View File

@@ -0,0 +1,135 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType;
import edu.wpi.first.wpilibj.communication.UsageReporting;
import edu.wpi.first.wpilibj.hal.AnalogJNI;
import java.nio.IntBuffer;
/**
* Class to represent a specific output from an analog trigger. This class is
* used to get the current output value and also as a DigitalSource to provide
* routing of an output to digital subsystems on the FPGA such as Counter,
* Encoder, and Interrupt.
*
* The TriggerState output indicates the primary output value of the trigger. If
* the analog signal is less than the lower limit, the output is false. If the
* analog value is greater than the upper limit, then the output is true. If the
* analog value is in between, then the trigger output state maintains its most
* recent value.
*
* The InWindow output indicates whether or not the analog signal is inside the
* range defined by the limits.
*
* The RisingPulse and FallingPulse outputs detect an instantaneous transition
* from above the upper limit to below the lower limit, and vise versa. These
* pulses represent a rollover condition of a sensor and can be routed to an up
* / down couter or to interrupts. Because the outputs generate a pulse, they
* cannot be read directly. To help ensure that a rollover condition is not
* missed, there is an average rejection filter available that operates on the
* upper 8 bits of a 12 bit number and selects the nearest outlyer of 3 samples.
* This will reject a sample that is (due to averaging or sampling) errantly
* between the two limits. This filter will fail if more than one sample in a
* row is errantly in between the two limits. You may see this problem if
* attempting to use this feature with a mechanical rollover sensor, such as a
* 360 degree no-stop potentiometer without signal conditioning, because the
* rollover transition is not sharp / clean enough. Using the averaging engine
* may help with this, but rotational speeds of the sensor will then be limited.
*/
public class AnalogTriggerOutput extends DigitalSource {
/**
* Exceptions dealing with improper operation of the Analog trigger output
*/
public class AnalogTriggerOutputException extends RuntimeException {
/**
* Create a new exception with the given message
*
* @param message the message to pass with the exception
*/
public AnalogTriggerOutputException(String message) {
super(message);
}
}
private final AnalogTrigger m_trigger;
private final AnalogTriggerType m_outputType;
/**
* Create an object that represents one of the four outputs from an analog
* trigger.
*
* Because this class derives from DigitalSource, it can be passed into
* routing functions for Counter, Encoder, etc.
*
* @param trigger The trigger for which this is an output.
* @param outputType An enum that specifies the output on the trigger to
* represent.
*/
public AnalogTriggerOutput(AnalogTrigger trigger, final AnalogTriggerType outputType) {
if (trigger == null)
throw new NullPointerException("Analog Trigger given was null");
if (outputType == null)
throw new NullPointerException("Analog Trigger Type given was null");
m_trigger = trigger;
m_outputType = outputType;
UsageReporting.report(tResourceType.kResourceType_AnalogTriggerOutput, trigger.getIndex(),
outputType.value);
}
@Override
public void free() {
}
/**
* Get the state of the analog trigger output.
*
* @return The state of the analog trigger output.
*/
public boolean get() {
return AnalogJNI.getAnalogTriggerOutput(m_trigger.m_port, m_outputType.value);
}
@Override
public int getChannelForRouting() {
return (m_trigger.m_index << 2) + m_outputType.value;
}
@Override
public byte getModuleForRouting() {
return (byte) (m_trigger.m_index >> 2);
}
@Override
public boolean getAnalogTriggerForRouting() {
return true;
}
/**
* Defines the state in which the AnalogTrigger triggers
*$
* @author jonathanleitschuh
*/
public enum AnalogTriggerType {
kInWindow(AnalogJNI.AnalogTriggerType.kInWindow), kState(AnalogJNI.AnalogTriggerType.kState), kRisingPulse(
AnalogJNI.AnalogTriggerType.kRisingPulse), kFallingPulse(
AnalogJNI.AnalogTriggerType.kFallingPulse);
private final int value;
private AnalogTriggerType(int value) {
this.value = value;
}
}
}

View File

@@ -0,0 +1,116 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2014. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import edu.wpi.first.wpilibj.interfaces.Accelerometer;
import edu.wpi.first.wpilibj.hal.AccelerometerJNI;
import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType;
import edu.wpi.first.wpilibj.communication.UsageReporting;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable;
import edu.wpi.first.wpilibj.tables.ITable;
/**
* Built-in accelerometer.
*
* This class allows access to the RoboRIO's internal accelerometer.
*/
public class BuiltInAccelerometer implements Accelerometer, LiveWindowSendable {
/**
* Constructor.
*$
* @param range The range the accelerometer will measure
*/
public BuiltInAccelerometer(Range range) {
setRange(range);
UsageReporting
.report(tResourceType.kResourceType_Accelerometer, 0, 0, "Built-in accelerometer");
LiveWindow.addSensor("BuiltInAccel", 0, this);
}
/**
* Constructor. The accelerometer will measure +/-8 g-forces
*/
public BuiltInAccelerometer() {
this(Range.k8G);
}
/** {inheritdoc} */
@Override
public void setRange(Range range) {
AccelerometerJNI.setAccelerometerActive(false);
switch (range) {
case k2G:
AccelerometerJNI.setAccelerometerRange(0);
break;
case k4G:
AccelerometerJNI.setAccelerometerRange(1);
break;
case k8G:
AccelerometerJNI.setAccelerometerRange(2);
break;
case k16G:
throw new RuntimeException("16G range not supported (use k2G, k4G, or k8G)");
}
AccelerometerJNI.setAccelerometerActive(true);
}
/**
* @return The acceleration of the RoboRIO along the X axis in g-forces
*/
@Override
public double getX() {
return AccelerometerJNI.getAccelerometerX();
}
/**
* @return The acceleration of the RoboRIO along the Y axis in g-forces
*/
@Override
public double getY() {
return AccelerometerJNI.getAccelerometerY();
}
/**
* @return The acceleration of the RoboRIO along the Z axis in g-forces
*/
@Override
public double getZ() {
return AccelerometerJNI.getAccelerometerZ();
}
public String getSmartDashboardType() {
return "3AxisAccelerometer";
}
private ITable m_table;
/** {@inheritDoc} */
public void initTable(ITable subtable) {
m_table = subtable;
updateTable();
}
/** {@inheritDoc} */
public void updateTable() {
if (m_table != null) {
m_table.putNumber("X", getX());
m_table.putNumber("Y", getY());
m_table.putNumber("Z", getZ());
}
}
/** {@inheritDoc} */
public ITable getTable() {
return m_table;
}
public void startLiveWindowMode() {}
public void stopLiveWindowMode() {}
};

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,190 @@
package edu.wpi.first.wpilibj;
import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable;
import edu.wpi.first.wpilibj.tables.ITable;
import edu.wpi.first.wpilibj.tables.ITableListener;
public interface CANSpeedController extends SpeedController, PIDInterface, LiveWindowSendable {
/**
* Mode determines how the motor is controlled, used internally. This is meant
* to be subclassed by enums
* (see {@link CANTalon.TalonControlMode CANTalon.TalonControlMode}).
*
*
* Note that the Jaguar does not support follower mode.
*/
public interface ControlMode {
/**
* Gets the name of this control mode. Since this interface should only be
* subclassed by enumerations, this will be overridden by the builtin
* name() method.
*/
public String name();
/**
* Checks if this control mode is PID-compatible.
*/
public boolean isPID();
/**
* Gets the integer value of this control mode.
*/
public int getValue();
}
/**
* Gets the current control mode.
*
* @return the current control mode
*/
public ControlMode getControlMode();
/**
* Sets the control mode of this speed controller.
*
* @param mode the the new mode
*/
public void setControlMode(int mode);
/**
* Set the proportional PID constant.
*/
public void setP(double p);
/**
* Set the integral PID constant.
*/
public void setI(double i);
/**
* Set the derivative PID constant.
*/
public void setD(double d);
/**
* Set the feed-forward PID constant. This method is optional to implement.
*/
public default void setF(double f) {
}
/**
* Gets the feed-forward PID constant. This method is optional to implement.
* If a subclass does not implement this, it will always return zero.
*/
public default double getF() {
return 0.0;
}
/**
* Get the current input (battery) voltage.
*
* @return the input voltage to the controller (in Volts).
*/
public double getBusVoltage();
/**
* Get the current output voltage.
*
* @return the output voltage to the motor in volts.
*/
public double getOutputVoltage();
/**
* Get the current being applied to the motor.
*
* @return the current motor current (in Amperes).
*/
public double getOutputCurrent();
/**
* Get the current temperature of the controller.
*
* @return the current temperature of the controller, in degrees Celsius.
*/
public double getTemperature();
/**
* Return the current position of whatever the current selected sensor is.
*
* See specific implementations for more information on selecting feedback
* sensors.
*
* @return the current sensor position.
*/
public double getPosition();
/**
* Return the current velocity of whatever the current selected sensor is.
*
* See specific implementations for more information on selecting feedback
* sensors.
*
* @return the current sensor velocity.
*/
public double getSpeed();
/**
* Set the maximum rate of change of the output voltage.
*
* @param rampRate the maximum rate of change of the votlage, in Volts / sec.
*/
public void setVoltageRampRate(double rampRate);
/**
* All CAN Speed Controllers have the same SmartDashboard type: "CANSpeedController".
*/
String SMART_DASHBOARD_TYPE = "CANSpeedController";
@Override
public default void updateTable() {
ITable table = getTable();
if(table != null) {
table.putString("~TYPE~", SMART_DASHBOARD_TYPE);
table.putString("Type", getClass().getSimpleName()); // "CANTalon", "CANJaguar"
table.putNumber("Mode", getControlMode().getValue());
if (getControlMode().isPID()) {
// CANJaguar throws an exception if you try to get its PID constants
// when it's not in a PID-compatible mode
table.putNumber("p", getP());
table.putNumber("i", getI());
table.putNumber("d", getD());
table.putNumber("f", getF());
}
table.putBoolean("Enabled", isEnabled());
table.putNumber("Value", get());
}
}
@Override
public default String getSmartDashboardType() {
return SMART_DASHBOARD_TYPE;
}
/**
* Creates an ITableListener for the LiveWindow table for this CAN speed
* controller.
*/
public default ITableListener createTableListener() {
return (table, key, value, isNew) -> {
switch(key) {
case "Enabled":
if ((Boolean) value) {
enable();
} else {
disable();
}
break;
case "Value": set((Double) value); break;
case "Mode": setControlMode(((Double) value).intValue()); break;
}
if(getControlMode().isPID()) {
switch(key) {
case "p": setP((Double) value); break;
case "i": setI((Double) value); break;
case "d": setD((Double) value); break;
case "f": setF((Double) value); break;
}
}
};
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,372 @@
package edu.wpi.first.wpilibj;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.concurrent.atomic.AtomicBoolean;
import com.ni.vision.NIVision;
import com.ni.vision.NIVision.Image;
import com.ni.vision.NIVision.RawData;
import com.ni.vision.VisionException;
import edu.wpi.first.wpilibj.DriverStation;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.vision.USBCamera;
// replicates CameraServer.cpp in java lib
public class CameraServer {
private static final int kPort = 1180;
private static final byte[] kMagicNumber = {0x01, 0x00, 0x00, 0x00};
private static final int kSize640x480 = 0;
private static final int kSize320x240 = 1;
private static final int kSize160x120 = 2;
private static final int kHardwareCompression = -1;
private static final String kDefaultCameraName = "cam1";
private static final int kMaxImageSize = 200000;
private static CameraServer server;
public static CameraServer getInstance() {
if (server == null) {
server = new CameraServer();
}
return server;
}
private Thread serverThread;
private int m_quality;
private boolean m_autoCaptureStarted;
private boolean m_hwClient = true;
private USBCamera m_camera;
private CameraData m_imageData;
private Deque<ByteBuffer> m_imageDataPool;
private class CameraData {
RawData data;
int start;
public CameraData(RawData d, int s) {
data = d;
start = s;
}
}
private CameraServer() {
m_quality = 50;
m_camera = null;
m_imageData = null;
m_imageDataPool = new ArrayDeque<>(3);
for (int i = 0; i < 3; i++) {
m_imageDataPool.addLast(ByteBuffer.allocateDirect(kMaxImageSize));
}
serverThread = new Thread(new Runnable() {
public void run() {
try {
serve();
} catch (IOException e) {
// do stuff here
} catch (InterruptedException e) {
// do stuff here
}
}
});
serverThread.setName("CameraServer Send Thread");
serverThread.start();
}
private synchronized void setImageData(RawData data, int start) {
if (m_imageData != null && m_imageData.data != null) {
m_imageData.data.free();
if (m_imageData.data.getBuffer() != null)
m_imageDataPool.addLast(m_imageData.data.getBuffer());
m_imageData = null;
}
m_imageData = new CameraData(data, start);
notifyAll();
}
/**
* Manually change the image that is served by the MJPEG stream. This can be
* called to pass custom annotated images to the dashboard. Note that, for
* 640x480 video, this method could take between 40 and 50 milliseconds to
* complete.
*
* This shouldn't be called if {@link #startAutomaticCapture} is called.
*
* @param image The IMAQ image to show on the dashboard
*/
public void setImage(Image image) {
// handle multi-threadedness
/* Flatten the IMAQ image to a JPEG */
RawData data =
NIVision.imaqFlatten(image, NIVision.FlattenType.FLATTEN_IMAGE,
NIVision.CompressionType.COMPRESSION_JPEG, 10 * m_quality);
ByteBuffer buffer = data.getBuffer();
boolean hwClient;
synchronized (this) {
hwClient = m_hwClient;
}
/* Find the start of the JPEG data */
int index = 0;
if (hwClient) {
while (index < buffer.limit() - 1) {
if ((buffer.get(index) & 0xff) == 0xFF && (buffer.get(index + 1) & 0xff) == 0xD8)
break;
index++;
}
}
if (buffer.limit() - index - 1 <= 2) {
throw new VisionException("data size of flattened image is less than 2. Try another camera! ");
}
setImageData(data, index);
}
/**
* Start automatically capturing images to send to the dashboard. You should
* call this method to just see a camera feed on the dashboard without doing
* any vision processing on the roboRIO. {@link #setImage} shouldn't be called
* after this is called. This overload calles
* {@link #startAutomaticCapture(String)} with the default camera name
*/
public void startAutomaticCapture() {
startAutomaticCapture(USBCamera.kDefaultCameraName);
}
/**
* Start automatically capturing images to send to the dashboard.
*
* You should call this method to just see a camera feed on the dashboard
* without doing any vision processing on the roboRIO. {@link #setImage}
* shouldn't be called after this is called.
*
* @param cameraName The name of the camera interface (e.g. "cam1")
*/
public void startAutomaticCapture(String cameraName) {
try {
USBCamera camera = new USBCamera(cameraName);
camera.openCamera();
startAutomaticCapture(camera);
} catch (VisionException ex) {
DriverStation.reportError(
"Error when starting the camera: " + cameraName + " " + ex.getMessage(), true);
}
}
public synchronized void startAutomaticCapture(USBCamera camera) {
if (m_autoCaptureStarted)
return;
m_autoCaptureStarted = true;
m_camera = camera;
m_camera.startCapture();
Thread captureThread = new Thread(new Runnable() {
@Override
public void run() {
capture();
}
});
captureThread.setName("Camera Capture Thread");
captureThread.start();
}
protected void capture() {
Image frame = NIVision.imaqCreateImage(NIVision.ImageType.IMAGE_RGB, 0);
while (true) {
boolean hwClient;
ByteBuffer dataBuffer = null;
synchronized (this) {
hwClient = m_hwClient;
if (hwClient) {
dataBuffer = m_imageDataPool.removeLast();
}
}
try {
if (hwClient && dataBuffer != null) {
// Reset the image buffer limit
dataBuffer.limit(dataBuffer.capacity() - 1);
m_camera.getImageData(dataBuffer);
setImageData(new RawData(dataBuffer), 0);
} else {
m_camera.getImage(frame);
setImage(frame);
}
} catch (VisionException ex) {
DriverStation.reportError("Error when getting image from the camera: " + ex.getMessage(),
true);
if (dataBuffer != null) {
synchronized (this) {
m_imageDataPool.addLast(dataBuffer);
Timer.delay(.1);
}
}
}
}
}
/**
* check if auto capture is started
*
*/
public synchronized boolean isAutoCaptureStarted() {
return m_autoCaptureStarted;
}
/**
* Sets the size of the image to use. Use the public kSize constants to set
* the correct mode, or set it directory on a camera and call the appropriate
* autoCapture method
*$
* @param size The size to use
*/
public synchronized void setSize(int size) {
if (m_camera == null)
return;
switch (size) {
case kSize640x480:
m_camera.setSize(640, 480);
break;
case kSize320x240:
m_camera.setSize(320, 240);
break;
case kSize160x120:
m_camera.setSize(160, 120);
break;
}
}
/**
* Set the quality of the compressed image sent to the dashboard
*
* @param quality The quality of the JPEG image, from 0 to 100
*/
public synchronized void setQuality(int quality) {
m_quality = quality > 100 ? 100 : quality < 0 ? 0 : quality;
}
/**
* Get the quality of the compressed image sent to the dashboard
*
* @return The quality, from 0 to 100
*/
public synchronized int getQuality() {
return m_quality;
}
/**
* Run the M-JPEG server.
*
* This function listens for a connection from the dashboard in a background
* thread, then sends back the M-JPEG stream.
*
* @throws IOException if the Socket connection fails
* @throws InterruptedException if the sleep is interrupted
*/
protected void serve() throws IOException, InterruptedException {
ServerSocket socket = new ServerSocket();
socket.setReuseAddress(true);
InetSocketAddress address = new InetSocketAddress(kPort);
socket.bind(address);
while (true) {
try {
Socket s = socket.accept();
DataInputStream is = new DataInputStream(s.getInputStream());
DataOutputStream os = new DataOutputStream(s.getOutputStream());
int fps = is.readInt();
int compression = is.readInt();
int size = is.readInt();
if (compression != kHardwareCompression) {
DriverStation.reportError("Choose \"USB Camera HW\" on the dashboard", false);
s.close();
continue;
}
// Wait for the camera
synchronized (this) {
System.out.println("Camera not yet ready, awaiting image");
if (m_camera == null)
wait();
m_hwClient = compression == kHardwareCompression;
if (!m_hwClient)
setQuality(100 - compression);
else if (m_camera != null)
m_camera.setFPS(fps);
setSize(size);
}
long period = (long) (1000 / (1.0 * fps));
while (true) {
long t0 = System.currentTimeMillis();
CameraData imageData = null;
synchronized (this) {
wait();
imageData = m_imageData;
m_imageData = null;
}
if (imageData == null)
continue;
// Set the buffer position to the start of the data,
// and then create a new wrapper for the data at
// exactly that position
imageData.data.getBuffer().position(imageData.start);
byte[] imageArray = new byte[imageData.data.getBuffer().remaining()];
imageData.data.getBuffer().get(imageArray, 0, imageData.data.getBuffer().remaining());
// write numbers
try {
os.write(kMagicNumber);
os.writeInt(imageArray.length);
os.write(imageArray);
os.flush();
long dt = System.currentTimeMillis() - t0;
if (dt < period) {
Thread.sleep(period - dt);
}
} catch (IOException | UnsupportedOperationException ex) {
DriverStation.reportError(ex.getMessage(), true);
break;
} finally {
imageData.data.free();
if (imageData.data.getBuffer() != null) {
synchronized (this) {
m_imageDataPool.addLast(imageData.data.getBuffer());
}
}
}
}
} catch (IOException ex) {
DriverStation.reportError(ex.getMessage(), true);
continue;
}
}
}
}

View File

@@ -0,0 +1,745 @@
/*
* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org). Version
* 2.0.11
*$
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* -----------------------------------------------------------------------------
*/
package edu.wpi.first.wpilibj.hal;
public class CanTalonSRX extends CtreCanNode {
private long swigCPtr;
protected CanTalonSRX(long cPtr, boolean cMemoryOwn) {
super(CanTalonJNI.CanTalonSRX_SWIGUpcast(cPtr), cMemoryOwn);
swigCPtr = cPtr;
}
protected static long getCPtr(CanTalonSRX obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
protected void finalize() {
delete();
}
public synchronized void delete() {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CanTalonJNI.delete_CanTalonSRX(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public CanTalonSRX(int deviceNumber, int controlPeriodMs) {
this(CanTalonJNI.new_CanTalonSRX__SWIG_0(deviceNumber, controlPeriodMs), true);
}
public CanTalonSRX(int deviceNumber) {
this(CanTalonJNI.new_CanTalonSRX__SWIG_1(deviceNumber), true);
}
public CanTalonSRX() {
this(CanTalonJNI.new_CanTalonSRX__SWIG_2(), true);
}
public void Set(double value) {
CanTalonJNI.CanTalonSRX_Set(swigCPtr, this, value);
}
public SWIGTYPE_p_CTR_Code SetParam(CanTalonSRX.param_t paramEnum, double value) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetParam(swigCPtr, this,
paramEnum.swigValue(), value), true);
}
public SWIGTYPE_p_CTR_Code RequestParam(CanTalonSRX.param_t paramEnum) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_RequestParam(swigCPtr, this,
paramEnum.swigValue()), true);
}
public SWIGTYPE_p_CTR_Code GetParamResponse(CanTalonSRX.param_t paramEnum, SWIGTYPE_p_double value) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetParamResponse(swigCPtr, this,
paramEnum.swigValue(), SWIGTYPE_p_double.getCPtr(value)), true);
}
public SWIGTYPE_p_CTR_Code GetParamResponseInt32(CanTalonSRX.param_t paramEnum,
SWIGTYPE_p_int value) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetParamResponseInt32(swigCPtr, this,
paramEnum.swigValue(), SWIGTYPE_p_int.getCPtr(value)), true);
}
public SWIGTYPE_p_CTR_Code SetPgain(long slotIdx, double gain) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetPgain(swigCPtr, this, slotIdx, gain),
true);
}
public SWIGTYPE_p_CTR_Code SetIgain(long slotIdx, double gain) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetIgain(swigCPtr, this, slotIdx, gain),
true);
}
public SWIGTYPE_p_CTR_Code SetDgain(long slotIdx, double gain) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetDgain(swigCPtr, this, slotIdx, gain),
true);
}
public SWIGTYPE_p_CTR_Code SetFgain(long slotIdx, double gain) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetFgain(swigCPtr, this, slotIdx, gain),
true);
}
public SWIGTYPE_p_CTR_Code SetIzone(long slotIdx, int zone) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetIzone(swigCPtr, this, slotIdx, zone),
true);
}
public SWIGTYPE_p_CTR_Code SetCloseLoopRampRate(long slotIdx, int closeLoopRampRate) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetCloseLoopRampRate(swigCPtr, this,
slotIdx, closeLoopRampRate), true);
}
public SWIGTYPE_p_CTR_Code SetVoltageCompensationRate(double vpers) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetVoltageCompensationRate(swigCPtr, this,vpers), true);
}
public SWIGTYPE_p_CTR_Code SetSensorPosition(int pos) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetSensorPosition(swigCPtr, this, pos),true);
}
public SWIGTYPE_p_CTR_Code SetForwardSoftLimit(int forwardLimit) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetForwardSoftLimit(swigCPtr, this,
forwardLimit), true);
}
public SWIGTYPE_p_CTR_Code SetReverseSoftLimit(int reverseLimit) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetReverseSoftLimit(swigCPtr, this,
reverseLimit), true);
}
public SWIGTYPE_p_CTR_Code SetForwardSoftEnable(int enable) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetForwardSoftEnable(swigCPtr, this,
enable), true);
}
public SWIGTYPE_p_CTR_Code SetReverseSoftEnable(int enable) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetReverseSoftEnable(swigCPtr, this,
enable), true);
}
public SWIGTYPE_p_CTR_Code GetPgain(long slotIdx, SWIGTYPE_p_double gain) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetPgain(swigCPtr, this, slotIdx,
SWIGTYPE_p_double.getCPtr(gain)), true);
}
public SWIGTYPE_p_CTR_Code GetIgain(long slotIdx, SWIGTYPE_p_double gain) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetIgain(swigCPtr, this, slotIdx,
SWIGTYPE_p_double.getCPtr(gain)), true);
}
public SWIGTYPE_p_CTR_Code GetDgain(long slotIdx, SWIGTYPE_p_double gain) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetDgain(swigCPtr, this, slotIdx,
SWIGTYPE_p_double.getCPtr(gain)), true);
}
public SWIGTYPE_p_CTR_Code GetFgain(long slotIdx, SWIGTYPE_p_double gain) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetFgain(swigCPtr, this, slotIdx,
SWIGTYPE_p_double.getCPtr(gain)), true);
}
public SWIGTYPE_p_CTR_Code GetIzone(long slotIdx, SWIGTYPE_p_int zone) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetIzone(swigCPtr, this, slotIdx,
SWIGTYPE_p_int.getCPtr(zone)), true);
}
public SWIGTYPE_p_CTR_Code GetCloseLoopRampRate(long slotIdx, SWIGTYPE_p_int closeLoopRampRate) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetCloseLoopRampRate(swigCPtr, this,
slotIdx, SWIGTYPE_p_int.getCPtr(closeLoopRampRate)), true);
}
public SWIGTYPE_p_CTR_Code GetVoltageCompensationRate(SWIGTYPE_p_double vpers) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetVoltageCompensationRate(swigCPtr, this,
SWIGTYPE_p_double.getCPtr(vpers)), true);
}
public SWIGTYPE_p_CTR_Code GetForwardSoftLimit(SWIGTYPE_p_int forwardLimit) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetForwardSoftLimit(swigCPtr, this,
SWIGTYPE_p_int.getCPtr(forwardLimit)), true);
}
public SWIGTYPE_p_CTR_Code GetReverseSoftLimit(SWIGTYPE_p_int reverseLimit) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetReverseSoftLimit(swigCPtr, this,
SWIGTYPE_p_int.getCPtr(reverseLimit)), true);
}
public SWIGTYPE_p_CTR_Code GetForwardSoftEnable(SWIGTYPE_p_int enable) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetForwardSoftEnable(swigCPtr, this,
SWIGTYPE_p_int.getCPtr(enable)), true);
}
public SWIGTYPE_p_CTR_Code GetReverseSoftEnable(SWIGTYPE_p_int enable) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetReverseSoftEnable(swigCPtr, this,
SWIGTYPE_p_int.getCPtr(enable)), true);
}
public SWIGTYPE_p_CTR_Code SetStatusFrameRate(long frameEnum, long periodMs) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetStatusFrameRate(swigCPtr, this,
frameEnum, periodMs), true);
}
public SWIGTYPE_p_CTR_Code ClearStickyFaults() {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_ClearStickyFaults(swigCPtr, this), true);
}
public SWIGTYPE_p_CTR_Code GetFault_OverTemp(SWIGTYPE_p_int param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetFault_OverTemp(swigCPtr, this,
SWIGTYPE_p_int.getCPtr(param)), true);
}
public SWIGTYPE_p_CTR_Code GetFault_UnderVoltage(SWIGTYPE_p_int param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetFault_UnderVoltage(swigCPtr, this,
SWIGTYPE_p_int.getCPtr(param)), true);
}
public SWIGTYPE_p_CTR_Code GetFault_ForLim(SWIGTYPE_p_int param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetFault_ForLim(swigCPtr, this,
SWIGTYPE_p_int.getCPtr(param)), true);
}
public SWIGTYPE_p_CTR_Code GetFault_RevLim(SWIGTYPE_p_int param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetFault_RevLim(swigCPtr, this,
SWIGTYPE_p_int.getCPtr(param)), true);
}
public SWIGTYPE_p_CTR_Code GetFault_HardwareFailure(SWIGTYPE_p_int param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetFault_HardwareFailure(swigCPtr, this,
SWIGTYPE_p_int.getCPtr(param)), true);
}
public SWIGTYPE_p_CTR_Code GetFault_ForSoftLim(SWIGTYPE_p_int param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetFault_ForSoftLim(swigCPtr, this,
SWIGTYPE_p_int.getCPtr(param)), true);
}
public SWIGTYPE_p_CTR_Code GetFault_RevSoftLim(SWIGTYPE_p_int param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetFault_RevSoftLim(swigCPtr, this,
SWIGTYPE_p_int.getCPtr(param)), true);
}
public SWIGTYPE_p_CTR_Code GetStckyFault_OverTemp(SWIGTYPE_p_int param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetStckyFault_OverTemp(swigCPtr, this,
SWIGTYPE_p_int.getCPtr(param)), true);
}
public SWIGTYPE_p_CTR_Code GetStckyFault_UnderVoltage(SWIGTYPE_p_int param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetStckyFault_UnderVoltage(swigCPtr,
this, SWIGTYPE_p_int.getCPtr(param)), true);
}
public SWIGTYPE_p_CTR_Code GetStckyFault_ForLim(SWIGTYPE_p_int param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetStckyFault_ForLim(swigCPtr, this,
SWIGTYPE_p_int.getCPtr(param)), true);
}
public SWIGTYPE_p_CTR_Code GetStckyFault_RevLim(SWIGTYPE_p_int param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetStckyFault_RevLim(swigCPtr, this,
SWIGTYPE_p_int.getCPtr(param)), true);
}
public SWIGTYPE_p_CTR_Code GetStckyFault_ForSoftLim(SWIGTYPE_p_int param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetStckyFault_ForSoftLim(swigCPtr, this,
SWIGTYPE_p_int.getCPtr(param)), true);
}
public SWIGTYPE_p_CTR_Code GetStckyFault_RevSoftLim(SWIGTYPE_p_int param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetStckyFault_RevSoftLim(swigCPtr, this,
SWIGTYPE_p_int.getCPtr(param)), true);
}
public SWIGTYPE_p_CTR_Code GetAppliedThrottle(SWIGTYPE_p_int param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetAppliedThrottle(swigCPtr, this,
SWIGTYPE_p_int.getCPtr(param)), true);
}
public SWIGTYPE_p_CTR_Code GetCloseLoopErr(SWIGTYPE_p_int param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetCloseLoopErr(swigCPtr, this,
SWIGTYPE_p_int.getCPtr(param)), true);
}
public SWIGTYPE_p_CTR_Code GetFeedbackDeviceSelect(SWIGTYPE_p_int param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetFeedbackDeviceSelect(swigCPtr, this,
SWIGTYPE_p_int.getCPtr(param)), true);
}
public SWIGTYPE_p_CTR_Code GetModeSelect(SWIGTYPE_p_int param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetModeSelect(swigCPtr, this,
SWIGTYPE_p_int.getCPtr(param)), true);
}
public SWIGTYPE_p_CTR_Code GetLimitSwitchEn(SWIGTYPE_p_int param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetLimitSwitchEn(swigCPtr, this,
SWIGTYPE_p_int.getCPtr(param)), true);
}
public SWIGTYPE_p_CTR_Code GetLimitSwitchClosedFor(SWIGTYPE_p_int param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetLimitSwitchClosedFor(swigCPtr, this,
SWIGTYPE_p_int.getCPtr(param)), true);
}
public SWIGTYPE_p_CTR_Code GetLimitSwitchClosedRev(SWIGTYPE_p_int param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetLimitSwitchClosedRev(swigCPtr, this,
SWIGTYPE_p_int.getCPtr(param)), true);
}
public SWIGTYPE_p_CTR_Code GetSensorPosition(SWIGTYPE_p_int param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetSensorPosition(swigCPtr, this,
SWIGTYPE_p_int.getCPtr(param)), true);
}
public SWIGTYPE_p_CTR_Code GetSensorVelocity(SWIGTYPE_p_int param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetSensorVelocity(swigCPtr, this,
SWIGTYPE_p_int.getCPtr(param)), true);
}
public SWIGTYPE_p_CTR_Code GetCurrent(SWIGTYPE_p_double param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetCurrent(swigCPtr, this,
SWIGTYPE_p_double.getCPtr(param)), true);
}
public SWIGTYPE_p_CTR_Code GetBrakeIsEnabled(SWIGTYPE_p_int param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetBrakeIsEnabled(swigCPtr, this,
SWIGTYPE_p_int.getCPtr(param)), true);
}
public SWIGTYPE_p_CTR_Code GetEncPosition(SWIGTYPE_p_int param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetEncPosition(swigCPtr, this,
SWIGTYPE_p_int.getCPtr(param)), true);
}
public SWIGTYPE_p_CTR_Code GetEncVel(SWIGTYPE_p_int param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetEncVel(swigCPtr, this,
SWIGTYPE_p_int.getCPtr(param)), true);
}
public SWIGTYPE_p_CTR_Code GetEncIndexRiseEvents(SWIGTYPE_p_int param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetEncIndexRiseEvents(swigCPtr, this,
SWIGTYPE_p_int.getCPtr(param)), true);
}
public SWIGTYPE_p_CTR_Code GetQuadApin(SWIGTYPE_p_int param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetQuadApin(swigCPtr, this,
SWIGTYPE_p_int.getCPtr(param)), true);
}
public SWIGTYPE_p_CTR_Code GetQuadBpin(SWIGTYPE_p_int param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetQuadBpin(swigCPtr, this,
SWIGTYPE_p_int.getCPtr(param)), true);
}
public SWIGTYPE_p_CTR_Code GetQuadIdxpin(SWIGTYPE_p_int param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetQuadIdxpin(swigCPtr, this,
SWIGTYPE_p_int.getCPtr(param)), true);
}
public SWIGTYPE_p_CTR_Code GetAnalogInWithOv(SWIGTYPE_p_int param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetAnalogInWithOv(swigCPtr, this,
SWIGTYPE_p_int.getCPtr(param)), true);
}
public SWIGTYPE_p_CTR_Code GetAnalogInVel(SWIGTYPE_p_int param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetAnalogInVel(swigCPtr, this,
SWIGTYPE_p_int.getCPtr(param)), true);
}
public SWIGTYPE_p_CTR_Code GetTemp(SWIGTYPE_p_double param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetTemp(swigCPtr, this,
SWIGTYPE_p_double.getCPtr(param)), true);
}
public SWIGTYPE_p_CTR_Code GetBatteryV(SWIGTYPE_p_double param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetBatteryV(swigCPtr, this,
SWIGTYPE_p_double.getCPtr(param)), true);
}
public SWIGTYPE_p_CTR_Code GetResetCount(SWIGTYPE_p_int param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetResetCount(swigCPtr, this,
SWIGTYPE_p_int.getCPtr(param)), true);
}
public SWIGTYPE_p_CTR_Code GetResetFlags(SWIGTYPE_p_int param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetResetFlags(swigCPtr, this,
SWIGTYPE_p_int.getCPtr(param)), true);
}
public SWIGTYPE_p_CTR_Code GetFirmVers(SWIGTYPE_p_int param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetFirmVers(swigCPtr, this,
SWIGTYPE_p_int.getCPtr(param)), true);
}
public SWIGTYPE_p_CTR_Code SetDemand(int param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetDemand(swigCPtr, this, param), true);
}
public SWIGTYPE_p_CTR_Code SetOverrideLimitSwitchEn(int param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetOverrideLimitSwitchEn(swigCPtr, this,
param), true);
}
public SWIGTYPE_p_CTR_Code SetFeedbackDeviceSelect(int param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetFeedbackDeviceSelect(swigCPtr, this,
param), true);
}
public SWIGTYPE_p_CTR_Code SetRevMotDuringCloseLoopEn(int param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetRevMotDuringCloseLoopEn(swigCPtr,
this, param), true);
}
public SWIGTYPE_p_CTR_Code SetOverrideBrakeType(int param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetOverrideBrakeType(swigCPtr, this,
param), true);
}
public SWIGTYPE_p_CTR_Code SetModeSelect(int param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetModeSelect(swigCPtr, this, param),
true);
}
public SWIGTYPE_p_CTR_Code SetProfileSlotSelect(int param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetProfileSlotSelect(swigCPtr, this,
param), true);
}
public SWIGTYPE_p_CTR_Code SetRampThrottle(int param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetRampThrottle(swigCPtr, this, param),
true);
}
public SWIGTYPE_p_CTR_Code SetRevFeedbackSensor(int param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetRevFeedbackSensor(swigCPtr, this,
param), true);
}
public SWIGTYPE_p_CTR_Code GetPulseWidthPosition(SWIGTYPE_p_int param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetPulseWidthPosition(swigCPtr, this,
SWIGTYPE_p_int.getCPtr(param)), true);
}
public SWIGTYPE_p_CTR_Code GetPulseWidthVelocity(SWIGTYPE_p_int param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetPulseWidthVelocity(swigCPtr, this,
SWIGTYPE_p_int.getCPtr(param)), true);
}
public SWIGTYPE_p_CTR_Code GetPulseWidthRiseToFallUs(SWIGTYPE_p_int param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetPulseWidthRiseToFallUs(swigCPtr, this,
SWIGTYPE_p_int.getCPtr(param)), true);
}
public SWIGTYPE_p_CTR_Code GetPulseWidthRiseToRiseUs(SWIGTYPE_p_int param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetPulseWidthRiseToRiseUs(swigCPtr, this,
SWIGTYPE_p_int.getCPtr(param)), true);
}
public SWIGTYPE_p_CTR_Code IsPulseWidthSensorPresent(SWIGTYPE_p_int param) {
return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_IsPulseWidthSensorPresent(swigCPtr, this,
SWIGTYPE_p_int.getCPtr(param)), true);
}
public final static int kDefaultControlPeriodMs = CanTalonJNI
.CanTalonSRX_kDefaultControlPeriodMs_get();
public final static int kMode_DutyCycle = CanTalonJNI.CanTalonSRX_kMode_DutyCycle_get();
public final static int kMode_PositionCloseLoop = CanTalonJNI
.CanTalonSRX_kMode_PositionCloseLoop_get();
public final static int kMode_VelocityCloseLoop = CanTalonJNI
.CanTalonSRX_kMode_VelocityCloseLoop_get();
public final static int kMode_CurrentCloseLoop = CanTalonJNI
.CanTalonSRX_kMode_CurrentCloseLoop_get();
public final static int kMode_VoltCompen = CanTalonJNI.CanTalonSRX_kMode_VoltCompen_get();
public final static int kMode_SlaveFollower = CanTalonJNI.CanTalonSRX_kMode_SlaveFollower_get();
public final static int kMode_NoDrive = CanTalonJNI.CanTalonSRX_kMode_NoDrive_get();
public final static int kLimitSwitchOverride_UseDefaultsFromFlash = CanTalonJNI
.CanTalonSRX_kLimitSwitchOverride_UseDefaultsFromFlash_get();
public final static int kLimitSwitchOverride_DisableFwd_DisableRev = CanTalonJNI
.CanTalonSRX_kLimitSwitchOverride_DisableFwd_DisableRev_get();
public final static int kLimitSwitchOverride_DisableFwd_EnableRev = CanTalonJNI
.CanTalonSRX_kLimitSwitchOverride_DisableFwd_EnableRev_get();
public final static int kLimitSwitchOverride_EnableFwd_DisableRev = CanTalonJNI
.CanTalonSRX_kLimitSwitchOverride_EnableFwd_DisableRev_get();
public final static int kLimitSwitchOverride_EnableFwd_EnableRev = CanTalonJNI
.CanTalonSRX_kLimitSwitchOverride_EnableFwd_EnableRev_get();
public final static int kBrakeOverride_UseDefaultsFromFlash = CanTalonJNI
.CanTalonSRX_kBrakeOverride_UseDefaultsFromFlash_get();
public final static int kBrakeOverride_OverrideCoast = CanTalonJNI
.CanTalonSRX_kBrakeOverride_OverrideCoast_get();
public final static int kBrakeOverride_OverrideBrake = CanTalonJNI
.CanTalonSRX_kBrakeOverride_OverrideBrake_get();
public final static int kFeedbackDev_DigitalQuadEnc = CanTalonJNI
.CanTalonSRX_kFeedbackDev_DigitalQuadEnc_get();
public final static int kFeedbackDev_AnalogPot = CanTalonJNI
.CanTalonSRX_kFeedbackDev_AnalogPot_get();
public final static int kFeedbackDev_AnalogEncoder = CanTalonJNI
.CanTalonSRX_kFeedbackDev_AnalogEncoder_get();
public final static int kFeedbackDev_CountEveryRisingEdge = CanTalonJNI
.CanTalonSRX_kFeedbackDev_CountEveryRisingEdge_get();
public final static int kFeedbackDev_CountEveryFallingEdge = CanTalonJNI
.CanTalonSRX_kFeedbackDev_CountEveryFallingEdge_get();
public final static int kFeedbackDev_PosIsPulseWidth = CanTalonJNI
.CanTalonSRX_kFeedbackDev_PosIsPulseWidth_get();
public final static int kProfileSlotSelect_Slot0 = CanTalonJNI
.CanTalonSRX_kProfileSlotSelect_Slot0_get();
public final static int kProfileSlotSelect_Slot1 = CanTalonJNI
.CanTalonSRX_kProfileSlotSelect_Slot1_get();
public final static int kStatusFrame_General = CanTalonJNI.CanTalonSRX_kStatusFrame_General_get();
public final static int kStatusFrame_Feedback = CanTalonJNI
.CanTalonSRX_kStatusFrame_Feedback_get();
public final static int kStatusFrame_Encoder = CanTalonJNI.CanTalonSRX_kStatusFrame_Encoder_get();
public final static int kStatusFrame_AnalogTempVbat = CanTalonJNI
.CanTalonSRX_kStatusFrame_AnalogTempVbat_get();
public final static int kStatusFrame_PulseWidthMeas = CanTalonJNI
.CanTalonSRX_kStatusFrame_PulseWidthMeas_get();
public final static class param_t {
public final static CanTalonSRX.param_t eProfileParamSlot0_P = new CanTalonSRX.param_t(
"eProfileParamSlot0_P", CanTalonJNI.CanTalonSRX_eProfileParamSlot0_P_get());
public final static CanTalonSRX.param_t eProfileParamSlot0_I = new CanTalonSRX.param_t(
"eProfileParamSlot0_I", CanTalonJNI.CanTalonSRX_eProfileParamSlot0_I_get());
public final static CanTalonSRX.param_t eProfileParamSlot0_D = new CanTalonSRX.param_t(
"eProfileParamSlot0_D", CanTalonJNI.CanTalonSRX_eProfileParamSlot0_D_get());
public final static CanTalonSRX.param_t eProfileParamSlot0_F = new CanTalonSRX.param_t(
"eProfileParamSlot0_F", CanTalonJNI.CanTalonSRX_eProfileParamSlot0_F_get());
public final static CanTalonSRX.param_t eProfileParamSlot0_IZone = new CanTalonSRX.param_t(
"eProfileParamSlot0_IZone", CanTalonJNI.CanTalonSRX_eProfileParamSlot0_IZone_get());
public final static CanTalonSRX.param_t eProfileParamSlot0_CloseLoopRampRate =
new CanTalonSRX.param_t("eProfileParamSlot0_CloseLoopRampRate",
CanTalonJNI.CanTalonSRX_eProfileParamSlot0_CloseLoopRampRate_get());
public final static CanTalonSRX.param_t eProfileParamSlot1_P = new CanTalonSRX.param_t(
"eProfileParamSlot1_P", CanTalonJNI.CanTalonSRX_eProfileParamSlot1_P_get());
public final static CanTalonSRX.param_t eProfileParamSlot1_I = new CanTalonSRX.param_t(
"eProfileParamSlot1_I", CanTalonJNI.CanTalonSRX_eProfileParamSlot1_I_get());
public final static CanTalonSRX.param_t eProfileParamSlot1_D = new CanTalonSRX.param_t(
"eProfileParamSlot1_D", CanTalonJNI.CanTalonSRX_eProfileParamSlot1_D_get());
public final static CanTalonSRX.param_t eProfileParamSlot1_F = new CanTalonSRX.param_t(
"eProfileParamSlot1_F", CanTalonJNI.CanTalonSRX_eProfileParamSlot1_F_get());
public final static CanTalonSRX.param_t eProfileParamSlot1_IZone = new CanTalonSRX.param_t(
"eProfileParamSlot1_IZone", CanTalonJNI.CanTalonSRX_eProfileParamSlot1_IZone_get());
public final static CanTalonSRX.param_t eProfileParamSlot1_CloseLoopRampRate =
new CanTalonSRX.param_t("eProfileParamSlot1_CloseLoopRampRate",
CanTalonJNI.CanTalonSRX_eProfileParamSlot1_CloseLoopRampRate_get());
public final static CanTalonSRX.param_t eProfileParamSoftLimitForThreshold =
new CanTalonSRX.param_t("eProfileParamSoftLimitForThreshold",
CanTalonJNI.CanTalonSRX_eProfileParamSoftLimitForThreshold_get());
public final static CanTalonSRX.param_t eProfileParamSoftLimitRevThreshold =
new CanTalonSRX.param_t("eProfileParamSoftLimitRevThreshold",
CanTalonJNI.CanTalonSRX_eProfileParamSoftLimitRevThreshold_get());
public final static CanTalonSRX.param_t eProfileParamSoftLimitForEnable =
new CanTalonSRX.param_t("eProfileParamSoftLimitForEnable",
CanTalonJNI.CanTalonSRX_eProfileParamSoftLimitForEnable_get());
public final static CanTalonSRX.param_t eProfileParamSoftLimitRevEnable =
new CanTalonSRX.param_t("eProfileParamSoftLimitRevEnable",
CanTalonJNI.CanTalonSRX_eProfileParamSoftLimitRevEnable_get());
public final static CanTalonSRX.param_t eOnBoot_BrakeMode = new CanTalonSRX.param_t(
"eOnBoot_BrakeMode", CanTalonJNI.CanTalonSRX_eOnBoot_BrakeMode_get());
public final static CanTalonSRX.param_t eOnBoot_LimitSwitch_Forward_NormallyClosed =
new CanTalonSRX.param_t("eOnBoot_LimitSwitch_Forward_NormallyClosed",
CanTalonJNI.CanTalonSRX_eOnBoot_LimitSwitch_Forward_NormallyClosed_get());
public final static CanTalonSRX.param_t eOnBoot_LimitSwitch_Reverse_NormallyClosed =
new CanTalonSRX.param_t("eOnBoot_LimitSwitch_Reverse_NormallyClosed",
CanTalonJNI.CanTalonSRX_eOnBoot_LimitSwitch_Reverse_NormallyClosed_get());
public final static CanTalonSRX.param_t eOnBoot_LimitSwitch_Forward_Disable =
new CanTalonSRX.param_t("eOnBoot_LimitSwitch_Forward_Disable",
CanTalonJNI.CanTalonSRX_eOnBoot_LimitSwitch_Forward_Disable_get());
public final static CanTalonSRX.param_t eOnBoot_LimitSwitch_Reverse_Disable =
new CanTalonSRX.param_t("eOnBoot_LimitSwitch_Reverse_Disable",
CanTalonJNI.CanTalonSRX_eOnBoot_LimitSwitch_Reverse_Disable_get());
public final static CanTalonSRX.param_t eFault_OverTemp = new CanTalonSRX.param_t(
"eFault_OverTemp", CanTalonJNI.CanTalonSRX_eFault_OverTemp_get());
public final static CanTalonSRX.param_t eFault_UnderVoltage = new CanTalonSRX.param_t(
"eFault_UnderVoltage", CanTalonJNI.CanTalonSRX_eFault_UnderVoltage_get());
public final static CanTalonSRX.param_t eFault_ForLim = new CanTalonSRX.param_t(
"eFault_ForLim", CanTalonJNI.CanTalonSRX_eFault_ForLim_get());
public final static CanTalonSRX.param_t eFault_RevLim = new CanTalonSRX.param_t(
"eFault_RevLim", CanTalonJNI.CanTalonSRX_eFault_RevLim_get());
public final static CanTalonSRX.param_t eFault_HardwareFailure = new CanTalonSRX.param_t(
"eFault_HardwareFailure", CanTalonJNI.CanTalonSRX_eFault_HardwareFailure_get());
public final static CanTalonSRX.param_t eFault_ForSoftLim = new CanTalonSRX.param_t(
"eFault_ForSoftLim", CanTalonJNI.CanTalonSRX_eFault_ForSoftLim_get());
public final static CanTalonSRX.param_t eFault_RevSoftLim = new CanTalonSRX.param_t(
"eFault_RevSoftLim", CanTalonJNI.CanTalonSRX_eFault_RevSoftLim_get());
public final static CanTalonSRX.param_t eStckyFault_OverTemp = new CanTalonSRX.param_t(
"eStckyFault_OverTemp", CanTalonJNI.CanTalonSRX_eStckyFault_OverTemp_get());
public final static CanTalonSRX.param_t eStckyFault_UnderVoltage = new CanTalonSRX.param_t(
"eStckyFault_UnderVoltage", CanTalonJNI.CanTalonSRX_eStckyFault_UnderVoltage_get());
public final static CanTalonSRX.param_t eStckyFault_ForLim = new CanTalonSRX.param_t(
"eStckyFault_ForLim", CanTalonJNI.CanTalonSRX_eStckyFault_ForLim_get());
public final static CanTalonSRX.param_t eStckyFault_RevLim = new CanTalonSRX.param_t(
"eStckyFault_RevLim", CanTalonJNI.CanTalonSRX_eStckyFault_RevLim_get());
public final static CanTalonSRX.param_t eStckyFault_ForSoftLim = new CanTalonSRX.param_t(
"eStckyFault_ForSoftLim", CanTalonJNI.CanTalonSRX_eStckyFault_ForSoftLim_get());
public final static CanTalonSRX.param_t eStckyFault_RevSoftLim = new CanTalonSRX.param_t(
"eStckyFault_RevSoftLim", CanTalonJNI.CanTalonSRX_eStckyFault_RevSoftLim_get());
public final static CanTalonSRX.param_t eAppliedThrottle = new CanTalonSRX.param_t(
"eAppliedThrottle", CanTalonJNI.CanTalonSRX_eAppliedThrottle_get());
public final static CanTalonSRX.param_t eCloseLoopErr = new CanTalonSRX.param_t(
"eCloseLoopErr", CanTalonJNI.CanTalonSRX_eCloseLoopErr_get());
public final static CanTalonSRX.param_t eFeedbackDeviceSelect = new CanTalonSRX.param_t(
"eFeedbackDeviceSelect", CanTalonJNI.CanTalonSRX_eFeedbackDeviceSelect_get());
public final static CanTalonSRX.param_t eRevMotDuringCloseLoopEn = new CanTalonSRX.param_t(
"eRevMotDuringCloseLoopEn", CanTalonJNI.CanTalonSRX_eRevMotDuringCloseLoopEn_get());
public final static CanTalonSRX.param_t eModeSelect = new CanTalonSRX.param_t("eModeSelect",
CanTalonJNI.CanTalonSRX_eModeSelect_get());
public final static CanTalonSRX.param_t eProfileSlotSelect = new CanTalonSRX.param_t(
"eProfileSlotSelect", CanTalonJNI.CanTalonSRX_eProfileSlotSelect_get());
public final static CanTalonSRX.param_t eRampThrottle = new CanTalonSRX.param_t(
"eRampThrottle", CanTalonJNI.CanTalonSRX_eRampThrottle_get());
public final static CanTalonSRX.param_t eRevFeedbackSensor = new CanTalonSRX.param_t(
"eRevFeedbackSensor", CanTalonJNI.CanTalonSRX_eRevFeedbackSensor_get());
public final static CanTalonSRX.param_t eLimitSwitchEn = new CanTalonSRX.param_t(
"eLimitSwitchEn", CanTalonJNI.CanTalonSRX_eLimitSwitchEn_get());
public final static CanTalonSRX.param_t eLimitSwitchClosedFor = new CanTalonSRX.param_t(
"eLimitSwitchClosedFor", CanTalonJNI.CanTalonSRX_eLimitSwitchClosedFor_get());
public final static CanTalonSRX.param_t eLimitSwitchClosedRev = new CanTalonSRX.param_t(
"eLimitSwitchClosedRev", CanTalonJNI.CanTalonSRX_eLimitSwitchClosedRev_get());
public final static CanTalonSRX.param_t eSensorPosition = new CanTalonSRX.param_t(
"eSensorPosition", CanTalonJNI.CanTalonSRX_eSensorPosition_get());
public final static CanTalonSRX.param_t eSensorVelocity = new CanTalonSRX.param_t(
"eSensorVelocity", CanTalonJNI.CanTalonSRX_eSensorVelocity_get());
public final static CanTalonSRX.param_t eCurrent = new CanTalonSRX.param_t("eCurrent",
CanTalonJNI.CanTalonSRX_eCurrent_get());
public final static CanTalonSRX.param_t eBrakeIsEnabled = new CanTalonSRX.param_t(
"eBrakeIsEnabled", CanTalonJNI.CanTalonSRX_eBrakeIsEnabled_get());
public final static CanTalonSRX.param_t eEncPosition = new CanTalonSRX.param_t("eEncPosition",
CanTalonJNI.CanTalonSRX_eEncPosition_get());
public final static CanTalonSRX.param_t eEncVel = new CanTalonSRX.param_t("eEncVel",
CanTalonJNI.CanTalonSRX_eEncVel_get());
public final static CanTalonSRX.param_t eEncIndexRiseEvents = new CanTalonSRX.param_t(
"eEncIndexRiseEvents", CanTalonJNI.CanTalonSRX_eEncIndexRiseEvents_get());
public final static CanTalonSRX.param_t eQuadApin = new CanTalonSRX.param_t("eQuadApin",
CanTalonJNI.CanTalonSRX_eQuadApin_get());
public final static CanTalonSRX.param_t eQuadBpin = new CanTalonSRX.param_t("eQuadBpin",
CanTalonJNI.CanTalonSRX_eQuadBpin_get());
public final static CanTalonSRX.param_t eQuadIdxpin = new CanTalonSRX.param_t("eQuadIdxpin",
CanTalonJNI.CanTalonSRX_eQuadIdxpin_get());
public final static CanTalonSRX.param_t eAnalogInWithOv = new CanTalonSRX.param_t(
"eAnalogInWithOv", CanTalonJNI.CanTalonSRX_eAnalogInWithOv_get());
public final static CanTalonSRX.param_t eAnalogInVel = new CanTalonSRX.param_t("eAnalogInVel",
CanTalonJNI.CanTalonSRX_eAnalogInVel_get());
public final static CanTalonSRX.param_t eTemp = new CanTalonSRX.param_t("eTemp",
CanTalonJNI.CanTalonSRX_eTemp_get());
public final static CanTalonSRX.param_t eBatteryV = new CanTalonSRX.param_t("eBatteryV",
CanTalonJNI.CanTalonSRX_eBatteryV_get());
public final static CanTalonSRX.param_t eResetCount = new CanTalonSRX.param_t("eResetCount",
CanTalonJNI.CanTalonSRX_eResetCount_get());
public final static CanTalonSRX.param_t eResetFlags = new CanTalonSRX.param_t("eResetFlags",
CanTalonJNI.CanTalonSRX_eResetFlags_get());
public final static CanTalonSRX.param_t eFirmVers = new CanTalonSRX.param_t("eFirmVers",
CanTalonJNI.CanTalonSRX_eFirmVers_get());
public final static CanTalonSRX.param_t eSettingsChanged = new CanTalonSRX.param_t(
"eSettingsChanged", CanTalonJNI.CanTalonSRX_eSettingsChanged_get());
public final static CanTalonSRX.param_t eQuadFilterEn = new CanTalonSRX.param_t(
"eQuadFilterEn", CanTalonJNI.CanTalonSRX_eQuadFilterEn_get());
public final static CanTalonSRX.param_t ePidIaccum = new CanTalonSRX.param_t("ePidIaccum",
CanTalonJNI.CanTalonSRX_ePidIaccum_get());
public final static CanTalonSRX.param_t eStatus1FrameRate = new CanTalonSRX.param_t("eStatus1FrameRate",
CanTalonJNI.CanTalonSRX_eStatus1FrameRate_get());
public final static CanTalonSRX.param_t eStatus2FrameRate = new CanTalonSRX.param_t("eStatus2FrameRate",
CanTalonJNI.CanTalonSRX_eStatus2FrameRate_get());
public final static CanTalonSRX.param_t eStatus3FrameRate = new CanTalonSRX.param_t("eStatus3FrameRate",
CanTalonJNI.CanTalonSRX_eStatus3FrameRate_get());
public final static CanTalonSRX.param_t eStatus4FrameRate = new CanTalonSRX.param_t("eStatus4FrameRate",
CanTalonJNI.CanTalonSRX_eStatus4FrameRate_get());
public final static CanTalonSRX.param_t eStatus6FrameRate = new CanTalonSRX.param_t("eStatus6FrameRate",
CanTalonJNI.CanTalonSRX_eStatus6FrameRate_get());
public final static CanTalonSRX.param_t eStatus7FrameRate = new CanTalonSRX.param_t("eStatus7FrameRate",
CanTalonJNI.CanTalonSRX_eStatus7FrameRate_get());
public final static CanTalonSRX.param_t eClearPositionOnIdx = new CanTalonSRX.param_t("eClearPositionOnIdx",
CanTalonJNI.CanTalonSRX_eClearPositionOnIdx_get());
public final static CanTalonSRX.param_t ePeakPosOutput = new CanTalonSRX.param_t("ePeakPosOutput",
CanTalonJNI.CanTalonSRX_ePeakPosOutput_get());
public final static CanTalonSRX.param_t eNominalPosOutput = new CanTalonSRX.param_t("eNominalPosOutput",
CanTalonJNI.CanTalonSRX_eNominalPosOutput_get());
public final static CanTalonSRX.param_t ePeakNegOutput = new CanTalonSRX.param_t("ePeakNegOutput",
CanTalonJNI.CanTalonSRX_ePeakNegOutput_get());
public final static CanTalonSRX.param_t eNominalNegOutput = new CanTalonSRX.param_t("eNominalNegOutput",
CanTalonJNI.CanTalonSRX_eNominalNegOutput_get());
public final static CanTalonSRX.param_t eQuadIdxPolarity = new CanTalonSRX.param_t("eQuadIdxPolarity",
CanTalonJNI.CanTalonSRX_eQuadIdxPolarity_get());
public final static CanTalonSRX.param_t eStatus8FrameRate = new CanTalonSRX.param_t("eStatus8FrameRate",
CanTalonJNI.CanTalonSRX_eStatus8FrameRate_get());
public final static CanTalonSRX.param_t eAllowPosOverflow = new CanTalonSRX.param_t("eAllowPosOverflow",
CanTalonJNI.CanTalonSRX_eAllowPosOverflow_get());
public final static CanTalonSRX.param_t eProfileParamSlot0_AllowableClosedLoopErr = new CanTalonSRX.param_t("eProfileParamSlot0_AllowableClosedLoopErr",
CanTalonJNI.CanTalonSRX_eProfileParamSlot0_AllowableClosedLoopErr_get());
public final static CanTalonSRX.param_t eNumberPotTurns = new CanTalonSRX.param_t("eNumberPotTurns",
CanTalonJNI.CanTalonSRX_eNumberPotTurns_get());
public final static CanTalonSRX.param_t eNumberEncoderCPR = new CanTalonSRX.param_t("eNumberEncoderCPR",
CanTalonJNI.CanTalonSRX_eNumberEncoderCPR_get());
public final static CanTalonSRX.param_t ePwdPosition = new CanTalonSRX.param_t("ePwdPosition",
CanTalonJNI.CanTalonSRX_ePwdPosition_get());
public final static CanTalonSRX.param_t eAinPosition = new CanTalonSRX.param_t("eAinPosition",
CanTalonJNI.CanTalonSRX_eAinPosition_get());
public final static CanTalonSRX.param_t eProfileParamVcompRate = new CanTalonSRX.param_t("eProfileParamVcompRate",
CanTalonJNI.CanTalonSRX_eProfileParamVcompRate_get());
public final static CanTalonSRX.param_t eProfileParamSlot1_AllowableClosedLoopErr = new CanTalonSRX.param_t("eProfileParamSlot1_AllowableClosedLoopErr",
CanTalonJNI.CanTalonSRX_eProfileParamSlot1_AllowableClosedLoopErr_get());
public final int swigValue() {
return swigValue;
}
public String toString() {
return swigName;
}
public static param_t swigToEnum(int swigValue) {
if (swigValue < swigValues.length && swigValue >= 0
&& swigValues[swigValue].swigValue == swigValue)
return swigValues[swigValue];
for (int i = 0; i < swigValues.length; i++)
if (swigValues[i].swigValue == swigValue)
return swigValues[i];
throw new IllegalArgumentException("No enum " + param_t.class + " with value " + swigValue);
}
private param_t(String swigName) {
this.swigName = swigName;
this.swigValue = swigNext++;
}
private param_t(String swigName, int swigValue) {
this.swigName = swigName;
this.swigValue = swigValue;
swigNext = swigValue + 1;
}
private param_t(String swigName, param_t swigEnum) {
this.swigName = swigName;
this.swigValue = swigEnum.swigValue;
swigNext = this.swigValue + 1;
}
private static param_t[] swigValues = {eProfileParamSlot0_P, eProfileParamSlot0_I,
eProfileParamSlot0_D, eProfileParamSlot0_F, eProfileParamSlot0_IZone,
eProfileParamSlot0_CloseLoopRampRate, eProfileParamSlot1_P, eProfileParamSlot1_I,
eProfileParamSlot1_D, eProfileParamSlot1_F, eProfileParamSlot1_IZone,
eProfileParamSlot1_CloseLoopRampRate, eProfileParamSoftLimitForThreshold,
eProfileParamSoftLimitRevThreshold, eProfileParamSoftLimitForEnable,
eProfileParamSoftLimitRevEnable, eOnBoot_BrakeMode,
eOnBoot_LimitSwitch_Forward_NormallyClosed, eOnBoot_LimitSwitch_Reverse_NormallyClosed,
eOnBoot_LimitSwitch_Forward_Disable, eOnBoot_LimitSwitch_Reverse_Disable, eFault_OverTemp,
eFault_UnderVoltage, eFault_ForLim, eFault_RevLim, eFault_HardwareFailure,
eFault_ForSoftLim, eFault_RevSoftLim, eStckyFault_OverTemp, eStckyFault_UnderVoltage,
eStckyFault_ForLim, eStckyFault_RevLim, eStckyFault_ForSoftLim, eStckyFault_RevSoftLim,
eAppliedThrottle, eCloseLoopErr, eFeedbackDeviceSelect, eRevMotDuringCloseLoopEn,
eModeSelect, eProfileSlotSelect, eRampThrottle, eRevFeedbackSensor, eLimitSwitchEn,
eLimitSwitchClosedFor, eLimitSwitchClosedRev, eSensorPosition, eSensorVelocity, eCurrent,
eBrakeIsEnabled, eEncPosition, eEncVel, eEncIndexRiseEvents, eQuadApin, eQuadBpin,
eQuadIdxpin, eAnalogInWithOv, eAnalogInVel, eTemp, eBatteryV, eResetCount, eResetFlags,
eFirmVers, eSettingsChanged, eQuadFilterEn, ePidIaccum};
private static int swigNext = 0;
private final int swigValue;
private final String swigName;
}
}

View File

@@ -0,0 +1,210 @@
package edu.wpi.first.wpilibj;
import edu.wpi.first.wpilibj.SensorBase;
import edu.wpi.first.wpilibj.hal.CompressorJNI;
import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable;
import edu.wpi.first.wpilibj.tables.ITable;
/**
* Class for operating the PCM (Pneumatics compressor module) The PCM
* automatically will run in close-loop mode by default whenever a Solenoid
* object is created. For most cases the Compressor object does not need to be
* instantiated or used in a robot program.
*$
* This class is only required in cases where more detailed status or to
* enable/disable closed loop control. Note: you cannot operate the compressor
* directly from this class as doing so would circumvent the safety provided in
* using the pressure switch and closed loop control. You can only turn off
* closed loop control, thereby stopping the compressor from operating.
*/
public class Compressor extends SensorBase implements LiveWindowSendable {
private long m_pcm;
/**
* Create an instance of the Compressor
*$
* @param pcmId The PCM CAN device ID. Most robots that use PCM will have a
* single module. Use this for supporting a second module other than
* the default.
*/
public Compressor(int pcmId) {
initCompressor(pcmId);
}
/**
* Create an instance of the Compressor Makes a new instance of the compressor
* using the default PCM ID (0). Additional modules can be supported by making
* a new instance and specifying the CAN ID
*/
public Compressor() {
initCompressor(getDefaultSolenoidModule());
}
private void initCompressor(int module) {
m_table = null;
m_pcm = CompressorJNI.initializeCompressor((byte) module);
}
/**
* Start the compressor running in closed loop control mode Use the method in
* cases where you would like to manually stop and start the compressor for
* applications such as conserving battery or making sure that the compressor
* motor doesn't start during critical operations.
*/
public void start() {
setClosedLoopControl(true);
}
/**
* Stop the compressor from running in closed loop control mode. Use the
* method in cases where you would like to manually stop and start the
* compressor for applications such as conserving battery or making sure that
* the compressor motor doesn't start during critical operations.
*/
public void stop() {
setClosedLoopControl(false);
}
/**
* Get the enabled status of the compressor
*$
* @return true if the compressor is on
*/
public boolean enabled() {
return CompressorJNI.getCompressor(m_pcm);
}
/**
* Get the current pressure switch value
*$
* @return true if the pressure is low by reading the pressure switch that is
* plugged into the PCM
*/
public boolean getPressureSwitchValue() {
return CompressorJNI.getPressureSwitch(m_pcm);
}
/**
* Get the current being used by the compressor
*$
* @return current consumed in amps for the compressor motor
*/
public float getCompressorCurrent() {
return CompressorJNI.getCompressorCurrent(m_pcm);
}
/**
* Set the PCM in closed loop control mode
*$
* @param on If true sets the compressor to be in closed loop control mode
* otherwise normal operation of the compressor is disabled.
*/
public void setClosedLoopControl(boolean on) {
CompressorJNI.setClosedLoopControl(m_pcm, on);
}
/**
* Gets the current operating mode of the PCM
*$
* @return true if compressor is operating on closed-loop mode, otherwise
* return false.
*/
public boolean getClosedLoopControl() {
return CompressorJNI.getClosedLoopControl(m_pcm);
}
/**
* @return true if PCM is in fault state : Compressor Drive is disabled due to
* compressor current being too high.
*/
public boolean getCompressorCurrentTooHighFault() {
return CompressorJNI.getCompressorCurrentTooHighFault(m_pcm);
}
/**
* @return true if PCM sticky fault is set : Compressor Drive is disabled due
* to compressor current being too high.
*/
public boolean getCompressorCurrentTooHighStickyFault() {
return CompressorJNI.getCompressorCurrentTooHighStickyFault(m_pcm);
}
/**
* @return true if PCM sticky fault is set : Compressor output appears to be
* shorted.
*/
public boolean getCompressorShortedStickyFault() {
return CompressorJNI.getCompressorShortedStickyFault(m_pcm);
}
/**
* @return true if PCM is in fault state : Compressor output appears to be
* shorted.
*/
public boolean getCompressorShortedFault() {
return CompressorJNI.getCompressorShortedFault(m_pcm);
}
/**
* @return true if PCM sticky fault is set : Compressor does not appear to be
* wired, i.e. compressor is not drawing enough current.
*/
public boolean getCompressorNotConnectedStickyFault() {
return CompressorJNI.getCompressorNotConnectedStickyFault(m_pcm);
}
/**
* @return true if PCM is in fault state : Compressor does not appear to be
* wired, i.e. compressor is not drawing enough current.
*/
public boolean getCompressorNotConnectedFault() {
return CompressorJNI.getCompressorNotConnectedFault(m_pcm);
}
/**
* Clear ALL sticky faults inside PCM that Compressor is wired to.
*
* If a sticky fault is set, then it will be persistently cleared. Compressor
* drive maybe momentarily disable while flags are being cleared. Care should
* be taken to not call this too frequently, otherwise normal compressor
* functionality may be prevented.
*
* If no sticky faults are set then this call will have no effect.
*/
public void clearAllPCMStickyFaults() {
CompressorJNI.clearAllPCMStickyFaults(m_pcm);
}
@Override
public void startLiveWindowMode() {}
@Override
public void stopLiveWindowMode() {}
@Override
public String getSmartDashboardType() {
return "Compressor";
}
private ITable m_table;
@Override
public void initTable(ITable subtable) {
m_table = subtable;
updateTable();
}
@Override
public ITable getTable() {
return m_table;
}
@Override
public void updateTable() {
if (m_table != null) {
m_table.putBoolean("Enabled", enabled());
m_table.putBoolean("Pressure Switch", getPressureSwitchValue());
}
}
}

View File

@@ -0,0 +1,147 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import edu.wpi.first.wpilibj.hal.PowerJNI;
public class ControllerPower {
/**
* Get the input voltage to the robot controller
*$
* @return The controller input voltage value in Volts
*/
public static double getInputVoltage() {
return PowerJNI.getVinVoltage();
}
/**
* Get the input current to the robot controller
*$
* @return The controller input current value in Amps
*/
public static double getInputCurrent() {
return PowerJNI.getVinCurrent();
}
/**
* Get the voltage of the 3.3V rail
*$
* @return The controller 3.3V rail voltage value in Volts
*/
public static double getVoltage3V3() {
return PowerJNI.getUserVoltage3V3();
}
/**
* Get the current output of the 3.3V rail
*$
* @return The controller 3.3V rail output current value in Volts
*/
public static double getCurrent3V3() {
return PowerJNI.getUserCurrent3V3();
}
/**
* Get the enabled state of the 3.3V rail. The rail may be disabled due to a
* controller brownout, a short circuit on the rail, or controller
* over-voltage
*$
* @return The controller 3.3V rail enabled value
*/
public static boolean getEnabled3V3() {
return PowerJNI.getUserActive3V3();
}
/**
* Get the count of the total current faults on the 3.3V rail since the
* controller has booted
*$
* @return The number of faults
*/
public static int getFaultCount3V3() {
return PowerJNI.getUserCurrentFaults3V3();
}
/**
* Get the voltage of the 5V rail
*$
* @return The controller 5V rail voltage value in Volts
*/
public static double getVoltage5V() {
return PowerJNI.getUserVoltage5V();
}
/**
* Get the current output of the 5V rail
*$
* @return The controller 5V rail output current value in Amps
*/
public static double getCurrent5V() {
return PowerJNI.getUserCurrent5V();
}
/**
* Get the enabled state of the 5V rail. The rail may be disabled due to a
* controller brownout, a short circuit on the rail, or controller
* over-voltage
*$
* @return The controller 5V rail enabled value
*/
public static boolean getEnabled5V() {
return PowerJNI.getUserActive5V();
}
/**
* Get the count of the total current faults on the 5V rail since the
* controller has booted
*$
* @return The number of faults
*/
public static int getFaultCount5V() {
return PowerJNI.getUserCurrentFaults5V();
}
/**
* Get the voltage of the 6V rail
*$
* @return The controller 6V rail voltage value in Volts
*/
public static double getVoltage6V() {
return PowerJNI.getUserVoltage6V();
}
/**
* Get the current output of the 6V rail
*$
* @return The controller 6V rail output current value in Amps
*/
public static double getCurrent6V() {
return PowerJNI.getUserCurrent6V();
}
/**
* Get the enabled state of the 6V rail. The rail may be disabled due to a
* controller brownout, a short circuit on the rail, or controller
* over-voltage
*$
* @return The controller 6V rail enabled value
*/
public static boolean getEnabled6V() {
return PowerJNI.getUserActive6V();
}
/**
* Get the count of the total current faults on the 6V rail since the
* controller has booted
*$
* @return The number of faults
*/
public static int getFaultCount6V() {
return PowerJNI.getUserCurrentFaults6V();
}
}

View File

@@ -0,0 +1,632 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import edu.wpi.first.wpilibj.AnalogTriggerOutput.AnalogTriggerType;
import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType;
import edu.wpi.first.wpilibj.communication.UsageReporting;
import edu.wpi.first.wpilibj.hal.CounterJNI;
import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable;
import edu.wpi.first.wpilibj.tables.ITable;
import edu.wpi.first.wpilibj.util.BoundaryException;
/**
* Class for counting the number of ticks on a digital input channel. This is a
* general purpose class for counting repetitive events. It can return the
* number of counts, the period of the most recent cycle, and detect when the
* signal being counted has stopped by supplying a maximum cycle time.
*
* All counters will immediately start counting - reset() them if you need them
* to be zeroed before use.
*/
public class Counter extends SensorBase implements CounterBase, LiveWindowSendable, PIDSource {
/**
* Mode determines how and what the counter counts
*/
public static enum Mode {
/**
* mode: two pulse
*/
kTwoPulse(0),
/**
* mode: semi period
*/
kSemiperiod(1),
/**
* mode: pulse length
*/
kPulseLength(2),
/**
* mode: external direction
*/
kExternalDirection(3);
/**
* The integer value representing this enumeration
*/
public final int value;
private Mode(int value) {
this.value = value;
}
}
private DigitalSource m_upSource; // /< What makes the counter count up.
private DigitalSource m_downSource; // /< What makes the counter count down.
private boolean m_allocatedUpSource;
private boolean m_allocatedDownSource;
private long m_counter; // /< The FPGA counter object.
private int m_index; // /< The index of this counter.
private PIDSourceType m_pidSource;
private double m_distancePerPulse; // distance of travel for each tick
private void initCounter(final Mode mode) {
ByteBuffer index = ByteBuffer.allocateDirect(4);
// set the byte order
index.order(ByteOrder.LITTLE_ENDIAN);
m_counter = CounterJNI.initializeCounter(mode.value, index.asIntBuffer());
m_index = index.asIntBuffer().get(0);
m_allocatedUpSource = false;
m_allocatedDownSource = false;
m_upSource = null;
m_downSource = null;
setMaxPeriod(.5);
UsageReporting.report(tResourceType.kResourceType_Counter, m_index, mode.value);
}
/**
* Create an instance of a counter where no sources are selected. Then they
* all must be selected by calling functions to specify the upsource and the
* downsource independently.
*
* The counter will start counting immediately.
*/
public Counter() {
initCounter(Mode.kTwoPulse);
}
/**
* Create an instance of a counter from a Digital Input. This is used if an
* existing digital input is to be shared by multiple other objects such as
* encoders or if the Digital Source is not a DIO channel (such as an Analog
* Trigger)
*
* The counter will start counting immediately.
*
* @param source the digital source to count
*/
public Counter(DigitalSource source) {
if (source == null)
throw new NullPointerException("Digital Source given was null");
initCounter(Mode.kTwoPulse);
setUpSource(source);
}
/**
* Create an instance of a Counter object. Create an up-Counter instance given
* a channel.
*
* The counter will start counting immediately.
*
* @param channel the DIO channel to use as the up source. 0-9 are on-board,
* 10-25 are on the MXP
*/
public Counter(int channel) {
initCounter(Mode.kTwoPulse);
setUpSource(channel);
}
/**
* Create an instance of a Counter object. Create an instance of a simple
* up-Counter given an analog trigger. Use the trigger state output from the
* analog trigger.
*
* The counter will start counting immediately.
*
* @param encodingType which edges to count
* @param upSource first source to count
* @param downSource second source for direction
* @param inverted true to invert the count
*/
public Counter(EncodingType encodingType, DigitalSource upSource, DigitalSource downSource,
boolean inverted) {
initCounter(Mode.kExternalDirection);
if (encodingType != EncodingType.k1X && encodingType != EncodingType.k2X) {
throw new RuntimeException("Counters only support 1X and 2X quadreature decoding!");
}
if (upSource == null)
throw new NullPointerException("Up Source given was null");
setUpSource(upSource);
if (downSource == null)
throw new NullPointerException("Down Source given was null");
setDownSource(downSource);
if (encodingType == null)
throw new NullPointerException("Encoding type given was null");
if (encodingType == EncodingType.k1X) {
setUpSourceEdge(true, false);
CounterJNI.setCounterAverageSize(m_counter, 1);
} else {
setUpSourceEdge(true, true);
CounterJNI.setCounterAverageSize(m_counter, 2);
}
setDownSourceEdge(inverted, true);
}
/**
* Create an instance of a Counter object. Create an instance of a simple
* up-Counter given an analog trigger. Use the trigger state output from the
* analog trigger.
*
* The counter will start counting immediately.
*
* @param trigger the analog trigger to count
*/
public Counter(AnalogTrigger trigger) {
if (trigger == null) {
throw new NullPointerException("The Analog Trigger given was null");
}
initCounter(Mode.kTwoPulse);
setUpSource(trigger.createOutput(AnalogTriggerType.kState));
}
@Override
public void free() {
setUpdateWhenEmpty(true);
clearUpSource();
clearDownSource();
CounterJNI.freeCounter(m_counter);
m_upSource = null;
m_downSource = null;
m_counter = 0;
}
/**
* @return the Counter's FPGA index
*/
public int getFPGAIndex() {
return m_index;
}
/**
* Set the upsource for the counter as a digital input channel.
*
* @param channel the DIO channel to count 0-9 are on-board, 10-25 are on the
* MXP
*/
public void setUpSource(int channel) {
setUpSource(new DigitalInput(channel));
m_allocatedUpSource = true;
}
/**
* Set the source object that causes the counter to count up. Set the up
* counting DigitalSource.
*
* @param source the digital source to count
*/
public void setUpSource(DigitalSource source) {
if (m_upSource != null && m_allocatedUpSource) {
m_upSource.free();
m_allocatedUpSource = false;
}
m_upSource = source;
CounterJNI.setCounterUpSource(m_counter, source.getChannelForRouting(),
source.getAnalogTriggerForRouting());
}
/**
* Set the up counting source to be an analog trigger.
*
* @param analogTrigger The analog trigger object that is used for the Up
* Source
* @param triggerType The analog trigger output that will trigger the counter.
*/
public void setUpSource(AnalogTrigger analogTrigger, AnalogTriggerType triggerType) {
if (analogTrigger == null) {
throw new NullPointerException("Analog Trigger given was null");
}
if (triggerType == null) {
throw new NullPointerException("Analog Trigger Type given was null");
}
setUpSource(analogTrigger.createOutput(triggerType));
m_allocatedUpSource = true;
}
/**
* Set the edge sensitivity on an up counting source. Set the up source to
* either detect rising edges or falling edges.
*
* @param risingEdge true to count rising edge
* @param fallingEdge true to count falling edge
*/
public void setUpSourceEdge(boolean risingEdge, boolean fallingEdge) {
if (m_upSource == null)
throw new RuntimeException("Up Source must be set before setting the edge!");
CounterJNI.setCounterUpSourceEdge(m_counter, risingEdge, fallingEdge);
}
/**
* Disable the up counting source to the counter.
*/
public void clearUpSource() {
if (m_upSource != null && m_allocatedUpSource) {
m_upSource.free();
m_allocatedUpSource = false;
}
m_upSource = null;
CounterJNI.clearCounterUpSource(m_counter);
}
/**
* Set the down counting source to be a digital input channel.
*
* @param channel the DIO channel to count 0-9 are on-board, 10-25 are on the
* MXP
*/
public void setDownSource(int channel) {
setDownSource(new DigitalInput(channel));
m_allocatedDownSource = true;
}
/**
* Set the source object that causes the counter to count down. Set the down
* counting DigitalSource.
*
* @param source the digital source to count
*/
public void setDownSource(DigitalSource source) {
if (source == null) {
throw new NullPointerException("The Digital Source given was null");
}
if (m_downSource != null && m_allocatedDownSource) {
m_downSource.free();
m_allocatedDownSource = false;
}
CounterJNI.setCounterDownSource(m_counter, source.getChannelForRouting(),
source.getAnalogTriggerForRouting());
m_downSource = source;
}
/**
* Set the down counting source to be an analog trigger.
*
* @param analogTrigger The analog trigger object that is used for the Down
* Source
* @param triggerType The analog trigger output that will trigger the counter.
*/
public void setDownSource(AnalogTrigger analogTrigger, AnalogTriggerType triggerType) {
if (analogTrigger == null) {
throw new NullPointerException("Analog Trigger given was null");
}
if (triggerType == null) {
throw new NullPointerException("Analog Trigger Type given was null");
}
setDownSource(analogTrigger.createOutput(triggerType));
m_allocatedDownSource = true;
}
/**
* Set the edge sensitivity on a down counting source. Set the down source to
* either detect rising edges or falling edges.
*
* @param risingEdge true to count the rising edge
* @param fallingEdge true to count the falling edge
*/
public void setDownSourceEdge(boolean risingEdge, boolean fallingEdge) {
if (m_downSource == null)
throw new RuntimeException(" Down Source must be set before setting the edge!");
CounterJNI.setCounterDownSourceEdge(m_counter, risingEdge, fallingEdge);
}
/**
* Disable the down counting source to the counter.
*/
public void clearDownSource() {
if (m_downSource != null && m_allocatedDownSource) {
m_downSource.free();
m_allocatedDownSource = false;
}
m_downSource = null;
CounterJNI.clearCounterDownSource(m_counter);
}
/**
* Set standard up / down counting mode on this counter. Up and down counts
* are sourced independently from two inputs.
*/
public void setUpDownCounterMode() {
CounterJNI.setCounterUpDownMode(m_counter);
}
/**
* Set external direction mode on this counter. Counts are sourced on the Up
* counter input. The Down counter input represents the direction to count.
*/
public void setExternalDirectionMode() {
CounterJNI.setCounterExternalDirectionMode(m_counter);
}
/**
* Set Semi-period mode on this counter. Counts up on both rising and falling
* edges.
*
* @param highSemiPeriod true to count up on both rising and falling
*/
public void setSemiPeriodMode(boolean highSemiPeriod) {
CounterJNI.setCounterSemiPeriodMode(m_counter, highSemiPeriod);
}
/**
* Configure the counter to count in up or down based on the length of the
* input pulse. This mode is most useful for direction sensitive gear tooth
* sensors.
*
* @param threshold The pulse length beyond which the counter counts the
* opposite direction. Units are seconds.
*/
public void setPulseLengthMode(double threshold) {
CounterJNI.setCounterPulseLengthMode(m_counter, threshold);
}
/**
* Read the current counter value. Read the value at this instant. It may
* still be running, so it reflects the current value. Next time it is read,
* it might have a different value.
*/
@Override
public int get() {
return CounterJNI.getCounter(m_counter);
}
/**
* Read the current scaled counter value. Read the value at this instant,
* scaled by the distance per pulse (defaults to 1).
*
* @return The distance since the last reset
*/
public double getDistance() {
return get() * m_distancePerPulse;
}
/**
* Reset the Counter to zero. Set the counter value to zero. This doesn't
* effect the running state of the counter, just sets the current value to
* zero.
*/
@Override
public void reset() {
CounterJNI.resetCounter(m_counter);
}
/**
* Set the maximum period where the device is still considered "moving". Sets
* the maximum period where the device is considered moving. This value is
* used to determine the "stopped" state of the counter using the GetStopped
* method.
*
* @param maxPeriod The maximum period where the counted device is considered
* moving in seconds.
*/
@Override
public void setMaxPeriod(double maxPeriod) {
CounterJNI.setCounterMaxPeriod(m_counter, maxPeriod);
}
/**
* Select whether you want to continue updating the event timer output when
* there are no samples captured. The output of the event timer has a buffer
* of periods that are averaged and posted to a register on the FPGA. When the
* timer detects that the event source has stopped (based on the MaxPeriod)
* the buffer of samples to be averaged is emptied. If you enable the update
* when empty, you will be notified of the stopped source and the event time
* will report 0 samples. If you disable update when empty, the most recent
* average will remain on the output until a new sample is acquired. You will
* never see 0 samples output (except when there have been no events since an
* FPGA reset) and you will likely not see the stopped bit become true (since
* it is updated at the end of an average and there are no samples to
* average).
*
* @param enabled true to continue updating
*/
public void setUpdateWhenEmpty(boolean enabled) {
CounterJNI.setCounterUpdateWhenEmpty(m_counter, enabled);
}
/**
* Determine if the clock is stopped. Determine if the clocked input is
* stopped based on the MaxPeriod value set using the SetMaxPeriod method. If
* the clock exceeds the MaxPeriod, then the device (and counter) are assumed
* to be stopped and it returns true.
*
* @return Returns true if the most recent counter period exceeds the
* MaxPeriod value set by SetMaxPeriod.
*/
@Override
public boolean getStopped() {
return CounterJNI.getCounterStopped(m_counter);
}
/**
* The last direction the counter value changed.
*
* @return The last direction the counter value changed.
*/
@Override
public boolean getDirection() {
return CounterJNI.getCounterDirection(m_counter);
}
/**
* Set the Counter to return reversed sensing on the direction. This allows
* counters to change the direction they are counting in the case of 1X and 2X
* quadrature encoding only. Any other counter mode isn't supported.
*
* @param reverseDirection true if the value counted should be negated.
*/
public void setReverseDirection(boolean reverseDirection) {
CounterJNI.setCounterReverseDirection(m_counter, reverseDirection);
}
/**
* Get the Period of the most recent count. Returns the time interval of the
* most recent count. This can be used for velocity calculations to determine
* shaft speed.
*
* @return The period of the last two pulses in units of seconds.
*/
@Override
public double getPeriod() {
return CounterJNI.getCounterPeriod(m_counter);
}
/**
* Get the current rate of the Counter. Read the current rate of the counter
* accounting for the distance per pulse value. The default value for distance
* per pulse (1) yields units of pulses per second.
*
* @return The rate in units/sec
*/
public double getRate() {
return m_distancePerPulse / getPeriod();
}
/**
* Set the Samples to Average which specifies the number of samples of the
* timer to average when calculating the period. Perform averaging to account
* for mechanical imperfections or as oversampling to increase resolution.
*
* @param samplesToAverage The number of samples to average from 1 to 127.
*/
public void setSamplesToAverage(int samplesToAverage) {
CounterJNI.setCounterSamplesToAverage(m_counter, samplesToAverage);
}
/**
* Get the Samples to Average which specifies the number of samples of the
* timer to average when calculating the period. Perform averaging to account
* for mechanical imperfections or as oversampling to increase resolution.
*
* @return SamplesToAverage The number of samples being averaged (from 1 to
* 127)
*/
public int getSamplesToAverage() {
return CounterJNI.getCounterSamplesToAverage(m_counter);
}
/**
* Set the distance per pulse for this counter. This sets the multiplier used
* to determine the distance driven based on the count value from the encoder.
* Set this value based on the Pulses per Revolution and factor in any gearing
* reductions. This distance can be in any units you like, linear or angular.
*
* @param distancePerPulse The scale factor that will be used to convert
* pulses to useful units.
*/
public void setDistancePerPulse(double distancePerPulse) {
m_distancePerPulse = distancePerPulse;
}
/**
* Set which parameter of the encoder you are using as a process control
* variable. The counter class supports the rate and distance parameters.
*
* @param pidSource An enum to select the parameter.
*/
public void setPIDSourceType(PIDSourceType pidSource) {
if (pidSource == null) {
throw new NullPointerException("PID Source Parameter given was null");
}
BoundaryException.assertWithinBounds(pidSource.value, 0, 1);
m_pidSource = pidSource;
}
/**
* {@inheritDoc}
*/
public PIDSourceType getPIDSourceType() {
return m_pidSource;
}
@Override
public double pidGet() {
switch (m_pidSource) {
case kDisplacement:
return getDistance();
case kRate:
return getRate();
default:
return 0.0;
}
}
/**
* Live Window code, only does anything if live window is activated.
*/
@Override
public String getSmartDashboardType() {
return "Counter";
}
private ITable m_table;
/**
* {@inheritDoc}
*/
@Override
public void initTable(ITable subtable) {
m_table = subtable;
updateTable();
}
/**
* {@inheritDoc}
*/
@Override
public ITable getTable() {
return m_table;
}
/**
* {@inheritDoc}
*/
@Override
public void updateTable() {
if (m_table != null) {
m_table.putNumber("Value", get());
}
}
/**
* {@inheritDoc}
*/
@Override
public void startLiveWindowMode() {}
/**
* {@inheritDoc}
*/
@Override
public void stopLiveWindowMode() {}
}

View File

@@ -0,0 +1,86 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
/**
* Interface for counting the number of ticks on a digital input channel.
* Encoders, Gear tooth sensors, and counters should all subclass this so it can
* be used to build more advanced classes for control and driving.
*
* All counters will immediately start counting - reset() them if you need them
* to be zeroed before use.
*/
public interface CounterBase {
/**
* The number of edges for the counterbase to increment or decrement on
*/
public enum EncodingType {
/**
* Count only the rising edge
*/
k1X(0),
/**
* Count both the rising and falling edge
*/
k2X(1),
/**
* Count rising and falling on both channels
*/
k4X(2);
/**
* The integer value representing this enumeration
*/
public final int value;
private EncodingType(int value) {
this.value = value;
}
}
/**
* Get the count
*$
* @return the count
*/
int get();
/**
* Reset the count to zero
*/
void reset();
/**
* Get the time between the last two edges counted
*$
* @return the time beteween the last two ticks in seconds
*/
double getPeriod();
/**
* Set the maximum time between edges to be considered stalled
*$
* @param maxPeriod the maximum period in seconds
*/
void setMaxPeriod(double maxPeriod);
/**
* Determine if the counter is not moving
*$
* @return true if the counter has not changed for the max period
*/
boolean getStopped();
/**
* Determine which direction the counter is going
*$
* @return true for one direction, false for the other
*/
boolean getDirection();
}

View File

@@ -0,0 +1,48 @@
/*
* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org). Version
* 2.0.11
*$
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* -----------------------------------------------------------------------------
*/
package edu.wpi.first.wpilibj.hal;
public class CtreCanNode {
private long swigCPtr;
protected boolean swigCMemOwn;
protected CtreCanNode(long cPtr, boolean cMemoryOwn) {
swigCMemOwn = cMemoryOwn;
swigCPtr = cPtr;
}
protected static long getCPtr(CtreCanNode obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
protected void finalize() {
delete();
}
public synchronized void delete() {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CanTalonJNI.delete_CtreCanNode(swigCPtr);
}
swigCPtr = 0;
}
}
public CtreCanNode(SWIGTYPE_p_UINT8 deviceNumber) {
this(CanTalonJNI.new_CtreCanNode(SWIGTYPE_p_UINT8.getCPtr(deviceNumber)), true);
}
public SWIGTYPE_p_UINT8 GetDeviceNumber() {
return new SWIGTYPE_p_UINT8(CanTalonJNI.CtreCanNode_GetDeviceNumber(swigCPtr, this), true);
}
}

View File

@@ -0,0 +1,112 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType;
import edu.wpi.first.wpilibj.communication.UsageReporting;
import edu.wpi.first.wpilibj.hal.DIOJNI;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable;
import edu.wpi.first.wpilibj.tables.ITable;
/**
* Class to read a digital input. This class will read digital inputs and return
* the current value on the channel. Other devices such as encoders, gear tooth
* sensors, etc. that are implemented elsewhere will automatically allocate
* digital inputs and outputs as required. This class is only for devices like
* switches etc. that aren't implemented anywhere else.
*/
public class DigitalInput extends DigitalSource implements LiveWindowSendable {
/**
* Create an instance of a Digital Input class. Creates a digital input given
* a channel.
*
* @param channel the DIO channel for the digital input 0-9 are on-board,
* 10-25 are on the MXP
*/
public DigitalInput(int channel) {
initDigitalPort(channel, true);
LiveWindow.addSensor("DigitalInput", channel, this);
UsageReporting.report(tResourceType.kResourceType_DigitalInput, channel);
}
/**
* Get the value from a digital input channel. Retrieve the value of a single
* digital input channel from the FPGA.
*
* @return the status of the digital input
*/
public boolean get() {
return DIOJNI.getDIO(m_port);
}
/**
* Get the channel of the digital input
*
* @return The GPIO channel number that this object represents.
*/
public int getChannel() {
return m_channel;
}
@Override
public boolean getAnalogTriggerForRouting() {
return false;
}
/*
* Live Window code, only does anything if live window is activated.
*/
@Override
public String getSmartDashboardType() {
return "Digital Input";
}
private ITable m_table;
/**
* {@inheritDoc}
*/
@Override
public void initTable(ITable subtable) {
m_table = subtable;
updateTable();
}
/**
* {@inheritDoc}
*/
@Override
public void updateTable() {
if (m_table != null) {
m_table.putBoolean("Value", get());
}
}
/**
* {@inheritDoc}
*/
@Override
public ITable getTable() {
return m_table;
}
/**
* {@inheritDoc}
*/
@Override
public void startLiveWindowMode() {}
/**
* {@inheritDoc}
*/
@Override
public void stopLiveWindowMode() {}
}

View File

@@ -0,0 +1,227 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import edu.wpi.first.wpilibj.communication.UsageReporting;
import edu.wpi.first.wpilibj.hal.DIOJNI;
import edu.wpi.first.wpilibj.hal.PWMJNI;
import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable;
import edu.wpi.first.wpilibj.tables.ITable;
import edu.wpi.first.wpilibj.tables.ITableListener;
import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType;
/**
* Class to write digital outputs. This class will write digital outputs. Other
* devices that are implemented elsewhere will automatically allocate digital
* inputs and outputs as required.
*/
public class DigitalOutput extends DigitalSource implements LiveWindowSendable {
private long m_pwmGenerator;
/**
* Create an instance of a digital output. Create an instance of a digital
* output given a channel.
*
* @param channel the DIO channel to use for the digital output. 0-9 are
* on-board, 10-25 are on the MXP
*/
public DigitalOutput(int channel) {
initDigitalPort(channel, false);
UsageReporting.report(tResourceType.kResourceType_DigitalOutput, channel);
}
/**
* Free the resources associated with a digital output.
*/
@Override
public void free() {
// disable the pwm only if we have allocated it
if (m_pwmGenerator != 0) {
disablePWM();
}
super.free();
}
/**
* Set the value of a digital output.
*
* @param value true is on, off is false
*/
public void set(boolean value) {
DIOJNI.setDIO(m_port, (short) (value ? 1 : 0));
}
/**
* @return The GPIO channel number that this object represents.
*/
public int getChannel() {
return m_channel;
}
/**
* Generate a single pulse. Write a pulse to the specified digital output
* channel. There can only be a single pulse going at any time.
*
* @param channel The channel to pulse.
* @param pulseLength The length of the pulse.
*/
public void pulse(final int channel, final float pulseLength) {
DIOJNI.pulse(m_port, pulseLength);
}
/**
* @deprecated Generate a single pulse. Write a pulse to the specified digital
* output channel. There can only be a single pulse going at any
* time.
*
* @param channel The channel to pulse.
* @param pulseLength The length of the pulse.
*/
@Deprecated
public void pulse(final int channel, final int pulseLength) {
float convertedPulse =
(float) (pulseLength / 1.0e9 * (DIOJNI.getLoopTiming() * 25));
System.err
.println("You should use the float version of pulse for portability. This is deprecated");
DIOJNI.pulse(m_port, convertedPulse);
}
/**
* Determine if the pulse is still going. Determine if a previously started
* pulse is still going.
*
* @return true if pulsing
*/
public boolean isPulsing() {
return DIOJNI.isPulsing(m_port);
}
/**
* Change the PWM frequency of the PWM output on a Digital Output line.
*
* The valid range is from 0.6 Hz to 19 kHz. The frequency resolution is
* logarithmic.
*
* There is only one PWM frequency for all channnels.
*
* @param rate The frequency to output all digital output PWM signals.
*/
public void setPWMRate(double rate) {
PWMJNI.setPWMRate(rate);
}
/**
* Enable a PWM Output on this line.
*
* Allocate one of the 6 DO PWM generator resources.
*
* Supply the initial duty-cycle to output so as to avoid a glitch when first
* starting.
*
* The resolution of the duty cycle is 8-bit for low frequencies (1kHz or
* less) but is reduced the higher the frequency of the PWM signal is.
*
* @param initialDutyCycle The duty-cycle to start generating. [0..1]
*/
public void enablePWM(double initialDutyCycle) {
if (m_pwmGenerator != 0)
return;
m_pwmGenerator = PWMJNI.allocatePWM();
PWMJNI.setPWMDutyCycle(m_pwmGenerator, initialDutyCycle);
PWMJNI.setPWMOutputChannel(m_pwmGenerator, m_channel);
}
/**
* Change this line from a PWM output back to a static Digital Output line.
*
* Free up one of the 6 DO PWM generator resources that were in use.
*/
public void disablePWM() {
if (m_pwmGenerator == 0)
return;
// Disable the output by routing to a dead bit.
PWMJNI.setPWMOutputChannel(m_pwmGenerator, kDigitalChannels);
PWMJNI.freePWM(m_pwmGenerator);
m_pwmGenerator = 0;
}
/**
* Change the duty-cycle that is being generated on the line.
*
* The resolution of the duty cycle is 8-bit for low frequencies (1kHz or
* less) but is reduced the higher the frequency of the PWM signal is.
*
* @param dutyCycle The duty-cycle to change to. [0..1]
*/
public void updateDutyCycle(double dutyCycle) {
if (m_pwmGenerator == 0)
return;
PWMJNI.setPWMDutyCycle(m_pwmGenerator, dutyCycle);
}
/*
* Live Window code, only does anything if live window is activated.
*/
@Override
public String getSmartDashboardType() {
return "Digital Output";
}
private ITable m_table;
private ITableListener m_table_listener;
/**
* {@inheritDoc}
*/
@Override
public void initTable(ITable subtable) {
m_table = subtable;
updateTable();
}
/**
* {@inheritDoc}
*/
@Override
public ITable getTable() {
return m_table;
}
/**
* {@inheritDoc}
*/
@Override
public void updateTable() {
// TODO: Put current value.
}
/**
* {@inheritDoc}
*/
@Override
public void startLiveWindowMode() {
m_table_listener = new ITableListener() {
@Override
public void valueChanged(ITable itable, String key, Object value, boolean bln) {
set(((Boolean) value).booleanValue());
}
};
m_table.addTableListener("Value", m_table_listener, true);
}
/**
* {@inheritDoc}
*/
@Override
public void stopLiveWindowMode() {
// TODO: Broken, should only remove the listener from "Value" only.
m_table.removeTableListener(m_table_listener);
}
}

View File

@@ -0,0 +1,82 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import edu.wpi.first.wpilibj.hal.DIOJNI;
import edu.wpi.first.wpilibj.util.AllocationException;
import edu.wpi.first.wpilibj.util.CheckedAllocationException;
/**
* DigitalSource Interface. The DigitalSource represents all the possible inputs
* for a counter or a quadrature encoder. The source may be either a digital
* input or an analog input. If the caller just provides a channel, then a
* digital input will be constructed and freed when finished for the source. The
* source can either be a digital input or analog trigger but not both.
*/
public abstract class DigitalSource extends InterruptableSensorBase {
protected static Resource channels = new Resource(kDigitalChannels);
protected long m_port;
protected int m_channel;
protected void initDigitalPort(int channel, boolean input) {
m_channel = channel;
checkDigitalChannel(m_channel); // XXX: Replace with
// HALLibrary.checkDigitalChannel when
// implemented
try {
channels.allocate(m_channel);
} catch (CheckedAllocationException ex) {
throw new AllocationException("Digital input " + m_channel + " is already allocated");
}
long port_pointer = DIOJNI.getPort((byte) channel);
m_port = DIOJNI.initializeDigitalPort(port_pointer);
DIOJNI.allocateDIO(m_port, input);
}
@Override
public void free() {
channels.free(m_channel);
DIOJNI.freeDIO(m_port);
m_channel = 0;
}
/**
* Get the channel routing number
*
* @return channel routing number
*/
@Override
public int getChannelForRouting() {
return m_channel;
}
/**
* Get the module routing number
*
* @return 0
*/
@Override
public byte getModuleForRouting() {
return 0;
}
/**
* Is this an analog trigger
*$
* @return true if this is an analog trigger
*/
@Override
public boolean getAnalogTriggerForRouting() {
return false;
}
}

View File

@@ -0,0 +1,234 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType;
import edu.wpi.first.wpilibj.communication.UsageReporting;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable;
import edu.wpi.first.wpilibj.tables.ITable;
import edu.wpi.first.wpilibj.tables.ITableListener;
import edu.wpi.first.wpilibj.util.AllocationException;
import edu.wpi.first.wpilibj.util.CheckedAllocationException;
/**
* DoubleSolenoid class for running 2 channels of high voltage Digital Output.
*
* The DoubleSolenoid class is typically used for pneumatics solenoids that have
* two positions controlled by two separate channels.
*/
public class DoubleSolenoid extends SolenoidBase implements LiveWindowSendable {
/**
* Possible values for a DoubleSolenoid
*/
public static enum Value {
kOff,
kForward,
kReverse
}
private int m_forwardChannel; // /< The forward channel on the module to
// control.
private int m_reverseChannel; // /< The reverse channel on the module to
// control.
private byte m_forwardMask; // /< The mask for the forward channel.
private byte m_reverseMask; // /< The mask for the reverse channel.
/**
* Common function to implement constructor behavior.
*/
private synchronized void initSolenoid() {
checkSolenoidModule(m_moduleNumber);
checkSolenoidChannel(m_forwardChannel);
checkSolenoidChannel(m_reverseChannel);
try {
m_allocated.allocate(m_moduleNumber * kSolenoidChannels + m_forwardChannel);
} catch (CheckedAllocationException e) {
throw new AllocationException("Solenoid channel " + m_forwardChannel + " on module "
+ m_moduleNumber + " is already allocated");
}
try {
m_allocated.allocate(m_moduleNumber * kSolenoidChannels + m_reverseChannel);
} catch (CheckedAllocationException e) {
throw new AllocationException("Solenoid channel " + m_reverseChannel + " on module "
+ m_moduleNumber + " is already allocated");
}
m_forwardMask = (byte) (1 << m_forwardChannel);
m_reverseMask = (byte) (1 << m_reverseChannel);
UsageReporting.report(tResourceType.kResourceType_Solenoid, m_forwardChannel, m_moduleNumber);
UsageReporting.report(tResourceType.kResourceType_Solenoid, m_reverseChannel, m_moduleNumber);
LiveWindow.addActuator("DoubleSolenoid", m_moduleNumber, m_forwardChannel, this);
}
/**
* Constructor. Uses the default PCM ID of 0
*$
* @param forwardChannel The forward channel number on the PCM (0..7).
* @param reverseChannel The reverse channel number on the PCM (0..7).
*/
public DoubleSolenoid(final int forwardChannel, final int reverseChannel) {
super(getDefaultSolenoidModule());
m_forwardChannel = forwardChannel;
m_reverseChannel = reverseChannel;
initSolenoid();
}
/**
* Constructor.
*
* @param moduleNumber The module number of the solenoid module to use.
* @param forwardChannel The forward channel on the module to control (0..7).
* @param reverseChannel The reverse channel on the module to control (0..7).
*/
public DoubleSolenoid(final int moduleNumber, final int forwardChannel, final int reverseChannel) {
super(moduleNumber);
m_forwardChannel = forwardChannel;
m_reverseChannel = reverseChannel;
initSolenoid();
}
/**
* Destructor.
*/
public synchronized void free() {
m_allocated.free(m_moduleNumber * kSolenoidChannels + m_forwardChannel);
m_allocated.free(m_moduleNumber * kSolenoidChannels + m_reverseChannel);
}
/**
* Set the value of a solenoid.
*
* @param value The value to set (Off, Forward, Reverse)
*/
public void set(final Value value) {
byte rawValue = 0;
switch (value) {
case kOff:
rawValue = 0x00;
break;
case kForward:
rawValue = m_forwardMask;
break;
case kReverse:
rawValue = m_reverseMask;
break;
}
set(rawValue, m_forwardMask | m_reverseMask);
}
/**
* Read the current value of the solenoid.
*
* @return The current value of the solenoid.
*/
public Value get() {
byte value = getAll();
if ((value & m_forwardMask) != 0)
return Value.kForward;
if ((value & m_reverseMask) != 0)
return Value.kReverse;
return Value.kOff;
}
/**
* Check if the forward solenoid is blacklisted. If a solenoid is shorted, it
* is added to the blacklist and disabled until power cycle, or until faults
* are cleared.
*
* @see #clearAllPCMStickyFaults()
*
* @return If solenoid is disabled due to short.
*/
public boolean isFwdSolenoidBlackListed() {
int blackList = getPCMSolenoidBlackList();
return ((blackList & m_forwardMask) != 0);
}
/**
* Check if the reverse solenoid is blacklisted. If a solenoid is shorted, it
* is added to the blacklist and disabled until power cycle, or until faults
* are cleared.
*
* @see #clearAllPCMStickyFaults()
*
* @return If solenoid is disabled due to short.
*/
public boolean isRevSolenoidBlackListed() {
int blackList = getPCMSolenoidBlackList();
return ((blackList & m_reverseMask) != 0);
}
/*
* Live Window code, only does anything if live window is activated.
*/
public String getSmartDashboardType() {
return "Double Solenoid";
}
private ITable m_table;
private ITableListener m_table_listener;
/**
* {@inheritDoc}
*/
public void initTable(ITable subtable) {
m_table = subtable;
updateTable();
}
/**
* {@inheritDoc}
*/
public ITable getTable() {
return m_table;
}
/**
* {@inheritDoc}
*/
public void updateTable() {
if (m_table != null) {
// TODO: this is bad
m_table.putString("Value", (get() == Value.kForward ? "Forward"
: (get() == Value.kReverse ? "Reverse" : "Off")));
}
}
/**
* {@inheritDoc}
*/
public void startLiveWindowMode() {
set(Value.kOff); // Stop for safety
m_table_listener = new ITableListener() {
public void valueChanged(ITable itable, String key, Object value, boolean bln) {
// TODO: this is bad also
if (value.toString().equals("Reverse"))
set(Value.kReverse);
else if (value.toString().equals("Forward"))
set(Value.kForward);
else
set(Value.kOff);
}
};
m_table.addTableListener("Value", m_table_listener, true);
}
/**
* {@inheritDoc}
*/
public void stopLiveWindowMode() {
set(Value.kOff); // Stop for safety
// TODO: Broken, should only remove the listener from "Value" only.
m_table.removeTableListener(m_table_listener);
}
}

View File

@@ -0,0 +1,659 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import java.nio.ByteBuffer;
import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary;
import edu.wpi.first.wpilibj.communication.HALControlWord;
import edu.wpi.first.wpilibj.communication.HALAllianceStationID;
import edu.wpi.first.wpilibj.hal.HALUtil;
import edu.wpi.first.wpilibj.hal.PowerJNI;
/**
* Provide access to the network communication data to / from the Driver
* Station.
*/
public class DriverStation implements RobotState.Interface {
/**
* Number of Joystick Ports
*/
public static final int kJoystickPorts = 6;
private class HALJoystickButtons {
public int buttons;
public byte count;
}
/**
* The robot alliance that the robot is a part of
*/
public enum Alliance {
Red, Blue, Invalid
}
private static final double JOYSTICK_UNPLUGGED_MESSAGE_INTERVAL = 1.0;
private double m_nextMessageTime = 0.0;
private static class DriverStationTask implements Runnable {
private DriverStation m_ds;
DriverStationTask(DriverStation ds) {
m_ds = ds;
}
public void run() {
m_ds.task();
}
} /* DriverStationTask */
private static DriverStation instance = new DriverStation();
private short[][] m_joystickAxes =
new short[kJoystickPorts][FRCNetworkCommunicationsLibrary.kMaxJoystickAxes];
private short[][] m_joystickPOVs =
new short[kJoystickPorts][FRCNetworkCommunicationsLibrary.kMaxJoystickPOVs];
private HALJoystickButtons[] m_joystickButtons = new HALJoystickButtons[kJoystickPorts];
private int[] m_joystickIsXbox = new int[kJoystickPorts];
private int[] m_joystickType = new int[kJoystickPorts];
private String[] m_joystickName = new String[kJoystickPorts];
private int[][] m_joystickAxisType =
new int[kJoystickPorts][FRCNetworkCommunicationsLibrary.kMaxJoystickAxes];
private Thread m_thread;
private final Object m_dataSem;
private volatile boolean m_thread_keepalive = true;
private boolean m_userInDisabled = false;
private boolean m_userInAutonomous = false;
private boolean m_userInTeleop = false;
private boolean m_userInTest = false;
private boolean m_newControlData;
private final long m_packetDataAvailableMutex;
private final long m_packetDataAvailableSem;
/**
* Gets an instance of the DriverStation
*
* @return The DriverStation.
*/
public static DriverStation getInstance() {
return DriverStation.instance;
}
/**
* DriverStation constructor.
*
* The single DriverStation instance is created statically with the instance
* static member variable.
*/
protected DriverStation() {
m_dataSem = new Object();
for (int i = 0; i < kJoystickPorts; i++) {
m_joystickButtons[i] = new HALJoystickButtons();
}
m_packetDataAvailableMutex = HALUtil.initializeMutexNormal();
m_packetDataAvailableSem = HALUtil.initializeMultiWait();
FRCNetworkCommunicationsLibrary.setNewDataSem(m_packetDataAvailableSem);
m_thread = new Thread(new DriverStationTask(this), "FRCDriverStation");
m_thread.setPriority((Thread.NORM_PRIORITY + Thread.MAX_PRIORITY) / 2);
m_thread.start();
}
/**
* Kill the thread
*/
public void release() {
m_thread_keepalive = false;
}
/**
* Provides the service routine for the DS polling thread.
*/
private void task() {
int safetyCounter = 0;
while (m_thread_keepalive) {
HALUtil.takeMultiWait(m_packetDataAvailableSem, m_packetDataAvailableMutex);
synchronized (this) {
getData();
}
synchronized (m_dataSem) {
m_dataSem.notifyAll();
}
if (++safetyCounter >= 4) {
MotorSafetyHelper.checkMotors();
safetyCounter = 0;
}
if (m_userInDisabled) {
FRCNetworkCommunicationsLibrary.FRCNetworkCommunicationObserveUserProgramDisabled();
}
if (m_userInAutonomous) {
FRCNetworkCommunicationsLibrary.FRCNetworkCommunicationObserveUserProgramAutonomous();
}
if (m_userInTeleop) {
FRCNetworkCommunicationsLibrary.FRCNetworkCommunicationObserveUserProgramTeleop();
}
if (m_userInTest) {
FRCNetworkCommunicationsLibrary.FRCNetworkCommunicationObserveUserProgramTest();
}
}
}
/**
* Wait for new data from the driver station.
*/
public void waitForData() {
waitForData(0);
}
/**
* Wait for new data or for timeout, which ever comes first. If timeout is 0,
* wait for new data only.
*
* @param timeout The maximum time in milliseconds to wait.
*/
public void waitForData(long timeout) {
synchronized (m_dataSem) {
try {
m_dataSem.wait(timeout);
} catch (InterruptedException ex) {
}
}
}
/**
* Copy data from the DS task for the user. If no new data exists, it will
* just be returned, otherwise the data will be copied from the DS polling
* loop.
*/
protected synchronized void getData() {
// Get the status of all of the joysticks
for (byte stick = 0; stick < kJoystickPorts; stick++) {
m_joystickAxes[stick] = FRCNetworkCommunicationsLibrary.HALGetJoystickAxes(stick);
m_joystickPOVs[stick] = FRCNetworkCommunicationsLibrary.HALGetJoystickPOVs(stick);
ByteBuffer countBuffer = ByteBuffer.allocateDirect(1);
m_joystickButtons[stick].buttons =
FRCNetworkCommunicationsLibrary.HALGetJoystickButtons((byte) stick, countBuffer);
m_joystickButtons[stick].count = countBuffer.get();
}
m_newControlData = true;
}
/**
* Read the battery voltage.
*
* @return The battery voltage in Volts.
*/
public double getBatteryVoltage() {
return PowerJNI.getVinVoltage();
}
/**
* Reports errors related to unplugged joysticks Throttles the errors so that
* they don't overwhelm the DS
*/
private void reportJoystickUnpluggedError(String message) {
double currentTime = Timer.getFPGATimestamp();
if (currentTime > m_nextMessageTime) {
reportError(message, false);
m_nextMessageTime = currentTime + JOYSTICK_UNPLUGGED_MESSAGE_INTERVAL;
}
}
/**
* Get the value of the axis on a joystick. This depends on the mapping of the
* joystick connected to the specified port.
*
* @param stick The joystick to read.
* @param axis The analog axis value to read from the joystick.
* @return The value of the axis on the joystick.
*/
public synchronized double getStickAxis(int stick, int axis) {
if (stick < 0 || stick >= kJoystickPorts) {
throw new RuntimeException("Joystick index is out of range, should be 0-5");
}
if (axis < 0 || axis >= FRCNetworkCommunicationsLibrary.kMaxJoystickAxes) {
throw new RuntimeException("Joystick axis is out of range");
}
if (axis >= m_joystickAxes[stick].length) {
reportJoystickUnpluggedError("WARNING: Joystick axis " + axis + " on port " + stick
+ " not available, check if controller is plugged in\n");
return 0.0;
}
byte value = (byte) m_joystickAxes[stick][axis];
if (value < 0) {
return value / 128.0;
} else {
return value / 127.0;
}
}
/**
* Returns the number of axes on a given joystick port
*
* @param stick The joystick port number
* @return The number of axes on the indicated joystick
*/
public synchronized int getStickAxisCount(int stick) {
if (stick < 0 || stick >= kJoystickPorts) {
throw new RuntimeException("Joystick index is out of range, should be 0-5");
}
return m_joystickAxes[stick].length;
}
/**
* Get the state of a POV on the joystick.
*
* @return the angle of the POV in degrees, or -1 if the POV is not pressed.
*/
public synchronized int getStickPOV(int stick, int pov) {
if (stick < 0 || stick >= kJoystickPorts) {
throw new RuntimeException("Joystick index is out of range, should be 0-5");
}
if (pov < 0 || pov >= FRCNetworkCommunicationsLibrary.kMaxJoystickPOVs) {
throw new RuntimeException("Joystick POV is out of range");
}
if (pov >= m_joystickPOVs[stick].length) {
reportJoystickUnpluggedError("WARNING: Joystick POV " + pov + " on port " + stick
+ " not available, check if controller is plugged in\n");
return -1;
}
return m_joystickPOVs[stick][pov];
}
/**
* Returns the number of POVs on a given joystick port
*
* @param stick The joystick port number
* @return The number of POVs on the indicated joystick
*/
public synchronized int getStickPOVCount(int stick) {
if (stick < 0 || stick >= kJoystickPorts) {
throw new RuntimeException("Joystick index is out of range, should be 0-5");
}
return m_joystickPOVs[stick].length;
}
/**
* The state of the buttons on the joystick.
*
* @param stick The joystick to read.
* @return The state of the buttons on the joystick.
*/
public synchronized int getStickButtons(final int stick) {
if (stick < 0 || stick >= kJoystickPorts) {
throw new RuntimeException("Joystick index is out of range, should be 0-3");
}
return m_joystickButtons[stick].buttons;
}
/**
* The state of one joystick button. Button indexes begin at 1.
*
* @param stick The joystick to read.
* @param button The button index, beginning at 1.
* @return The state of the joystick button.
*/
public synchronized boolean getStickButton(final int stick, byte button) {
if (stick < 0 || stick >= kJoystickPorts) {
throw new RuntimeException("Joystick index is out of range, should be 0-3");
}
if (button > m_joystickButtons[stick].count) {
reportJoystickUnpluggedError("WARNING: Joystick Button " + button + " on port " + stick
+ " not available, check if controller is plugged in\n");
return false;
}
if (button <= 0) {
reportJoystickUnpluggedError("ERROR: Button indexes begin at 1 in WPILib for C++ and Java\n");
return false;
}
return ((0x1 << (button - 1)) & m_joystickButtons[stick].buttons) != 0;
}
/**
* Gets the number of buttons on a joystick
*
* @param stick The joystick port number
* @return The number of buttons on the indicated joystick
*/
public synchronized int getStickButtonCount(int stick) {
if (stick < 0 || stick >= kJoystickPorts) {
throw new RuntimeException("Joystick index is out of range, should be 0-5");
}
return m_joystickButtons[stick].count;
}
/**
* Gets the value of isXbox on a joystick
*
* @param stick The joystick port number
* @return A boolean that returns the value of isXbox
*/
public synchronized boolean getJoystickIsXbox(int stick) {
if (stick < 0 || stick >= kJoystickPorts) {
throw new RuntimeException("Joystick index is out of range, should be 0-5");
}
// TODO: Remove this when calling for descriptor on empty stick no longer
// crashes
if (1 > m_joystickButtons[stick].count && 1 > m_joystickAxes[stick].length) {
reportJoystickUnpluggedError("WARNING: Joystick on port " + stick
+ " not available, check if controller is plugged in\n");
return false;
}
boolean retVal = false;
if (FRCNetworkCommunicationsLibrary.HALGetJoystickIsXbox((byte) stick) == 1) {
retVal = true;
}
return retVal;
}
/**
* Gets the value of type on a joystick
*
* @param stick The joystick port number
* @return The value of type
*/
public synchronized int getJoystickType(int stick) {
if (stick < 0 || stick >= kJoystickPorts) {
throw new RuntimeException("Joystick index is out of range, should be 0-5");
}
// TODO: Remove this when calling for descriptor on empty stick no longer
// crashes
if (1 > m_joystickButtons[stick].count && 1 > m_joystickAxes[stick].length) {
reportJoystickUnpluggedError("WARNING: Joystick on port " + stick
+ " not available, check if controller is plugged in\n");
return -1;
}
return FRCNetworkCommunicationsLibrary.HALGetJoystickType((byte) stick);
}
/**
* Gets the name of the joystick at a port
*
* @param stick The joystick port number
* @return The value of name
*/
public synchronized String getJoystickName(int stick) {
if (stick < 0 || stick >= kJoystickPorts) {
throw new RuntimeException("Joystick index is out of range, should be 0-5");
}
// TODO: Remove this when calling for descriptor on empty stick no longer
// crashes
if (1 > m_joystickButtons[stick].count && 1 > m_joystickAxes[stick].length) {
reportJoystickUnpluggedError("WARNING: Joystick on port " + stick
+ " not available, check if controller is plugged in\n");
return "";
}
return FRCNetworkCommunicationsLibrary.HALGetJoystickName((byte) stick);
}
/**
* Gets a value indicating whether the Driver Station requires the robot to be
* enabled.
*
* @return True if the robot is enabled, false otherwise.
*/
public boolean isEnabled() {
HALControlWord controlWord = FRCNetworkCommunicationsLibrary.HALGetControlWord();
return controlWord.getEnabled() && controlWord.getDSAttached();
}
/**
* Gets a value indicating whether the Driver Station requires the robot to be
* disabled.
*
* @return True if the robot should be disabled, false otherwise.
*/
public boolean isDisabled() {
return !isEnabled();
}
/**
* Gets a value indicating whether the Driver Station requires the robot to be
* running in autonomous mode.
*
* @return True if autonomous mode should be enabled, false otherwise.
*/
public boolean isAutonomous() {
HALControlWord controlWord = FRCNetworkCommunicationsLibrary.HALGetControlWord();
return controlWord.getAutonomous();
}
/**
* Gets a value indicating whether the Driver Station requires the robot to be
* running in test mode.
*$
* @return True if test mode should be enabled, false otherwise.
*/
public boolean isTest() {
HALControlWord controlWord = FRCNetworkCommunicationsLibrary.HALGetControlWord();
return controlWord.getTest();
}
/**
* Gets a value indicating whether the Driver Station requires the robot to be
* running in operator-controlled mode.
*
* @return True if operator-controlled mode should be enabled, false
* otherwise.
*/
public boolean isOperatorControl() {
return !(isAutonomous() || isTest());
}
/**
* Gets a value indicating whether the FPGA outputs are enabled. The outputs
* may be disabled if the robot is disabled or e-stopped, the watdhog has
* expired, or if the roboRIO browns out.
*
* @return True if the FPGA outputs are enabled.
*/
public boolean isSysActive() {
return FRCNetworkCommunicationsLibrary.HALGetSystemActive();
}
/**
* Check if the system is browned out.
*$
* @return True if the system is browned out
*/
public boolean isBrownedOut() {
return FRCNetworkCommunicationsLibrary.HALGetBrownedOut();
}
/**
* Has a new control packet from the driver station arrived since the last
* time this function was called?
*$
* @return True if the control data has been updated since the last call.
*/
public synchronized boolean isNewControlData() {
boolean result = m_newControlData;
m_newControlData = false;
return result;
}
/**
* Get the current alliance from the FMS
*$
* @return the current alliance
*/
public Alliance getAlliance() {
HALAllianceStationID allianceStationID =
FRCNetworkCommunicationsLibrary.HALGetAllianceStation();
if (allianceStationID == null) {
return Alliance.Invalid;
}
switch (allianceStationID) {
case Red1:
case Red2:
case Red3:
return Alliance.Red;
case Blue1:
case Blue2:
case Blue3:
return Alliance.Blue;
default:
return Alliance.Invalid;
}
}
/**
* Gets the location of the team's driver station controls.
*
* @return the location of the team's driver station controls: 1, 2, or 3
*/
public int getLocation() {
HALAllianceStationID allianceStationID =
FRCNetworkCommunicationsLibrary.HALGetAllianceStation();
if (allianceStationID == null) {
return 0;
}
switch (allianceStationID) {
case Red1:
case Blue1:
return 1;
case Red2:
case Blue2:
return 2;
case Blue3:
case Red3:
return 3;
default:
return 0;
}
}
/**
* Is the driver station attached to a Field Management System? Note: This
* does not work with the Blue DS.
*$
* @return True if the robot is competing on a field being controlled by a
* Field Management System
*/
public boolean isFMSAttached() {
HALControlWord controlWord = FRCNetworkCommunicationsLibrary.HALGetControlWord();
return controlWord.getFMSAttached();
}
public boolean isDSAttached() {
HALControlWord controlWord = FRCNetworkCommunicationsLibrary.HALGetControlWord();
return controlWord.getDSAttached();
}
/**
* Return the approximate match time The FMS does not send an official match
* time to the robots, but does send an approximate match time. The value will
* count down the time remaining in the current period (auto or teleop).
* Warning: This is not an official time (so it cannot be used to dispute ref
* calls or guarantee that a function will trigger before the match ends) The
* Practice Match function of the DS approximates the behaviour seen on the
* field.
*$
* @return Time remaining in current match period (auto or teleop) in seconds
*/
public double getMatchTime() {
return FRCNetworkCommunicationsLibrary.HALGetMatchTime();
}
/**
* Report error to Driver Station. Also prints error to System.err Optionally
* appends Stack trace to error message
*$
* @param printTrace If true, append stack trace to error string
*/
public static void reportError(String error, boolean printTrace) {
String errorString = error;
if (printTrace) {
errorString += " at ";
StackTraceElement[] traces = Thread.currentThread().getStackTrace();
for (int i = 2; i < traces.length; i++) {
errorString += traces[i].toString() + "\n";
}
}
System.err.println(errorString);
HALControlWord controlWord = FRCNetworkCommunicationsLibrary.HALGetControlWord();
if (controlWord.getDSAttached()) {
FRCNetworkCommunicationsLibrary.HALSetErrorData(errorString);
}
}
/**
* Only to be used to tell the Driver Station what code you claim to be
* executing for diagnostic purposes only
*$
* @param entering If true, starting disabled code; if false, leaving disabled
* code
*/
public void InDisabled(boolean entering) {
m_userInDisabled = entering;
}
/**
* Only to be used to tell the Driver Station what code you claim to be
* executing for diagnostic purposes only
*$
* @param entering If true, starting autonomous code; if false, leaving
* autonomous code
*/
public void InAutonomous(boolean entering) {
m_userInAutonomous = entering;
}
/**
* Only to be used to tell the Driver Station what code you claim to be
* executing for diagnostic purposes only
*$
* @param entering If true, starting teleop code; if false, leaving teleop
* code
*/
public void InOperatorControl(boolean entering) {
m_userInTeleop = entering;
}
/**
* Only to be used to tell the Driver Station what code you claim to be
* executing for diagnostic purposes only
*$
* @param entering If true, starting test code; if false, leaving test code
*/
public void InTest(boolean entering) {
m_userInTest = entering;
}
}

View File

@@ -0,0 +1,744 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import java.nio.ByteOrder;
import java.nio.ByteBuffer;
import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tInstances;
import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType;
import edu.wpi.first.wpilibj.communication.UsageReporting;
import edu.wpi.first.wpilibj.hal.EncoderJNI;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable;
import edu.wpi.first.wpilibj.tables.ITable;
import edu.wpi.first.wpilibj.util.BoundaryException;
/**
* Class to read quad encoders. Quadrature encoders are devices that count shaft
* rotation and can sense direction. The output of the QuadEncoder class is an
* integer that can count either up or down, and can go negative for reverse
* direction counting. When creating QuadEncoders, a direction is supplied that
* changes the sense of the output to make code more readable if the encoder is
* mounted such that forward movement generates negative values. Quadrature
* encoders have two digital outputs, an A Channel and a B Channel that are out
* of phase with each other to allow the FPGA to do direction sensing.
*
* All encoders will immediately start counting - reset() them if you need them
* to be zeroed before use.
*/
public class Encoder extends SensorBase implements CounterBase, PIDSource, LiveWindowSendable {
public enum IndexingType {
kResetWhileHigh, kResetWhileLow, kResetOnFallingEdge, kResetOnRisingEdge
}
/**
* The a source
*/
protected DigitalSource m_aSource; // the A phase of the quad encoder
/**
* The b source
*/
protected DigitalSource m_bSource; // the B phase of the quad encoder
/**
* The index source
*/
protected DigitalSource m_indexSource = null; // Index on some encoders
private long m_encoder;
private int m_index;
private double m_distancePerPulse; // distance of travel for each encoder
// tick
private Counter m_counter; // Counter object for 1x and 2x encoding
private EncodingType m_encodingType = EncodingType.k4X;
private int m_encodingScale; // 1x, 2x, or 4x, per the encodingType
private boolean m_allocatedA;
private boolean m_allocatedB;
private boolean m_allocatedI;
private PIDSourceType m_pidSource;
/**
* Common initialization code for Encoders. This code allocates resources for
* Encoders and is common to all constructors.
*
* The encoder will start counting immediately.
*
* @param reverseDirection If true, counts down instead of up (this is all
* relative)
* @param encodingType either k1X, k2X, or k4X to indicate 1X, 2X or 4X
* decoding. If 4X is selected, then an encoder FPGA object is used and
* the returned counts will be 4x the encoder spec'd value since all
* rising and falling edges are counted. If 1X or 2X are selected then
* a counter object will be used and the returned value will either
* exactly match the spec'd count or be double (2x) the spec'd count.
*/
private void initEncoder(boolean reverseDirection) {
switch (m_encodingType) {
case k4X:
m_encodingScale = 4;
ByteBuffer index = ByteBuffer.allocateDirect(4);
// set the byte order
index.order(ByteOrder.LITTLE_ENDIAN);
m_encoder =
EncoderJNI.initializeEncoder((byte) m_aSource.getModuleForRouting(), m_aSource
.getChannelForRouting(), m_aSource.getAnalogTriggerForRouting(),
(byte) m_bSource.getModuleForRouting(), m_bSource.getChannelForRouting(),
m_bSource.getAnalogTriggerForRouting(),
reverseDirection, index.asIntBuffer());
m_index = index.asIntBuffer().get(0);
m_counter = null;
setMaxPeriod(.5);
break;
case k2X:
case k1X:
m_encodingScale = m_encodingType == EncodingType.k1X ? 1 : 2;
m_counter = new Counter(m_encodingType, m_aSource, m_bSource, reverseDirection);
m_index = m_counter.getFPGAIndex();
break;
}
m_distancePerPulse = 1.0;
m_pidSource = PIDSourceType.kDisplacement;
UsageReporting.report(tResourceType.kResourceType_Encoder, m_index, m_encodingType.value);
LiveWindow.addSensor("Encoder", m_aSource.getChannelForRouting(), this);
}
/**
* Encoder constructor. Construct a Encoder given a and b channels.
*
* The encoder will start counting immediately.
*
* @param aChannel The a channel DIO channel. 0-9 are on-board, 10-25 are on
* the MXP port
* @param bChannel The b channel DIO channel. 0-9 are on-board, 10-25 are on
* the MXP port
* @param reverseDirection represents the orientation of the encoder and
* inverts the output values if necessary so forward represents
* positive values.
*/
public Encoder(final int aChannel, final int bChannel, boolean reverseDirection) {
m_allocatedA = true;
m_allocatedB = true;
m_allocatedI = false;
m_aSource = new DigitalInput(aChannel);
m_bSource = new DigitalInput(bChannel);
initEncoder(reverseDirection);
}
/**
* Encoder constructor. Construct a Encoder given a and b channels.
*
* The encoder will start counting immediately.
*
* @param aChannel The a channel digital input channel.
* @param bChannel The b channel digital input channel.
*/
public Encoder(final int aChannel, final int bChannel) {
this(aChannel, bChannel, false);
}
/**
* Encoder constructor. Construct a Encoder given a and b channels.
*
* The encoder will start counting immediately.
*
* @param aChannel The a channel digital input channel.
* @param bChannel The b channel digital input channel.
* @param reverseDirection represents the orientation of the encoder and
* inverts the output values if necessary so forward represents
* positive values.
* @param encodingType either k1X, k2X, or k4X to indicate 1X, 2X or 4X
* decoding. If 4X is selected, then an encoder FPGA object is used and
* the returned counts will be 4x the encoder spec'd value since all
* rising and falling edges are counted. If 1X or 2X are selected then
* a counter object will be used and the returned value will either
* exactly match the spec'd count or be double (2x) the spec'd count.
*/
public Encoder(final int aChannel, final int bChannel, boolean reverseDirection,
final EncodingType encodingType) {
m_allocatedA = true;
m_allocatedB = true;
m_allocatedI = false;
if (encodingType == null)
throw new NullPointerException("Given encoding type was null");
m_encodingType = encodingType;
m_aSource = new DigitalInput(aChannel);
m_bSource = new DigitalInput(bChannel);
initEncoder(reverseDirection);
}
/**
* Encoder constructor. Construct a Encoder given a and b channels. Using an
* index pulse forces 4x encoding
*
* The encoder will start counting immediately.
*
* @param aChannel The a channel digital input channel.
* @param bChannel The b channel digital input channel.
* @param indexChannel The index channel digital input channel.
* @param reverseDirection represents the orientation of the encoder and
* inverts the output values if necessary so forward represents
* positive values.
*/
public Encoder(final int aChannel, final int bChannel, final int indexChannel,
boolean reverseDirection) {
m_allocatedA = true;
m_allocatedB = true;
m_allocatedI = true;
m_aSource = new DigitalInput(aChannel);
m_bSource = new DigitalInput(bChannel);
m_indexSource = new DigitalInput(indexChannel);
initEncoder(reverseDirection);
setIndexSource(indexChannel);
}
/**
* Encoder constructor. Construct a Encoder given a and b channels. Using an
* index pulse forces 4x encoding
*
* The encoder will start counting immediately.
*
* @param aChannel The a channel digital input channel.
* @param bChannel The b channel digital input channel.
* @param indexChannel The index channel digital input channel.
*/
public Encoder(final int aChannel, final int bChannel, final int indexChannel) {
this(aChannel, bChannel, indexChannel, false);
}
/**
* Encoder constructor. Construct a Encoder given a and b channels as digital
* inputs. This is used in the case where the digital inputs are shared. The
* Encoder class will not allocate the digital inputs and assume that they
* already are counted.
*
* The encoder will start counting immediately.
*
* @param aSource The source that should be used for the a channel.
* @param bSource the source that should be used for the b channel.
* @param reverseDirection represents the orientation of the encoder and
* inverts the output values if necessary so forward represents
* positive values.
*/
public Encoder(DigitalSource aSource, DigitalSource bSource, boolean reverseDirection) {
m_allocatedA = false;
m_allocatedB = false;
m_allocatedI = false;
if (aSource == null)
throw new NullPointerException("Digital Source A was null");
m_aSource = aSource;
if (bSource == null)
throw new NullPointerException("Digital Source B was null");
m_bSource = bSource;
initEncoder(reverseDirection);
}
/**
* Encoder constructor. Construct a Encoder given a and b channels as digital
* inputs. This is used in the case where the digital inputs are shared. The
* Encoder class will not allocate the digital inputs and assume that they
* already are counted.
*
* The encoder will start counting immediately.
*
* @param aSource The source that should be used for the a channel.
* @param bSource the source that should be used for the b channel.
*/
public Encoder(DigitalSource aSource, DigitalSource bSource) {
this(aSource, bSource, false);
}
/**
* Encoder constructor. Construct a Encoder given a and b channels as digital
* inputs. This is used in the case where the digital inputs are shared. The
* Encoder class will not allocate the digital inputs and assume that they
* already are counted.
*
* The encoder will start counting immediately.
*
* @param aSource The source that should be used for the a channel.
* @param bSource the source that should be used for the b channel.
* @param reverseDirection represents the orientation of the encoder and
* inverts the output values if necessary so forward represents
* positive values.
* @param encodingType either k1X, k2X, or k4X to indicate 1X, 2X or 4X
* decoding. If 4X is selected, then an encoder FPGA object is used and
* the returned counts will be 4x the encoder spec'd value since all
* rising and falling edges are counted. If 1X or 2X are selected then
* a counter object will be used and the returned value will either
* exactly match the spec'd count or be double (2x) the spec'd count.
*/
public Encoder(DigitalSource aSource, DigitalSource bSource, boolean reverseDirection,
final EncodingType encodingType) {
m_allocatedA = false;
m_allocatedB = false;
m_allocatedI = false;
if (encodingType == null)
throw new NullPointerException("Given encoding type was null");
m_encodingType = encodingType;
if (aSource == null)
throw new NullPointerException("Digital Source A was null");
m_aSource = aSource;
if (bSource == null)
throw new NullPointerException("Digital Source B was null");
m_aSource = aSource;
m_bSource = bSource;
initEncoder(reverseDirection);
}
/**
* Encoder constructor. Construct a Encoder given a, b and index channels as
* digital inputs. This is used in the case where the digital inputs are
* shared. The Encoder class will not allocate the digital inputs and assume
* that they already are counted.
*
* The encoder will start counting immediately.
*
* @param aSource The source that should be used for the a channel.
* @param bSource the source that should be used for the b channel.
* @param indexSource the source that should be used for the index channel.
* @param reverseDirection represents the orientation of the encoder and
* inverts the output values if necessary so forward represents
* positive values.
*/
public Encoder(DigitalSource aSource, DigitalSource bSource, DigitalSource indexSource,
boolean reverseDirection) {
m_allocatedA = false;
m_allocatedB = false;
m_allocatedI = false;
if (aSource == null)
throw new NullPointerException("Digital Source A was null");
m_aSource = aSource;
if (bSource == null)
throw new NullPointerException("Digital Source B was null");
m_aSource = aSource;
m_bSource = bSource;
m_indexSource = indexSource;
initEncoder(reverseDirection);
setIndexSource(indexSource);
}
/**
* Encoder constructor. Construct a Encoder given a, b and index channels as
* digital inputs. This is used in the case where the digital inputs are
* shared. The Encoder class will not allocate the digital inputs and assume
* that they already are counted.
*
* The encoder will start counting immediately.
*
* @param aSource The source that should be used for the a channel.
* @param bSource the source that should be used for the b channel.
* @param indexSource the source that should be used for the index channel.
*/
public Encoder(DigitalSource aSource, DigitalSource bSource, DigitalSource indexSource) {
this(aSource, bSource, indexSource, false);
}
/**
* @return the Encoder's FPGA index
*/
public int getFPGAIndex() {
return m_index;
}
/**
* @return the encoding scale factor 1x, 2x, or 4x, per the requested
* encodingType. Used to divide raw edge counts down to spec'd counts.
*/
public int getEncodingScale() {
return m_encodingScale;
}
public void free() {
if (m_aSource != null && m_allocatedA) {
m_aSource.free();
m_allocatedA = false;
}
if (m_bSource != null && m_allocatedB) {
m_bSource.free();
m_allocatedB = false;
}
if (m_indexSource != null && m_allocatedI) {
m_indexSource.free();
m_allocatedI = false;
}
m_aSource = null;
m_bSource = null;
m_indexSource = null;
if (m_counter != null) {
m_counter.free();
m_counter = null;
} else {
EncoderJNI.freeEncoder(m_encoder);
}
}
/**
* Gets the raw value from the encoder. The raw value is the actual count
* unscaled by the 1x, 2x, or 4x scale factor.
*
* @return Current raw count from the encoder
*/
public int getRaw() {
int value;
if (m_counter != null) {
value = m_counter.get();
} else {
value = EncoderJNI.getEncoder(m_encoder);
}
return value;
}
/**
* Gets the current count. Returns the current count on the Encoder. This
* method compensates for the decoding type.
*
* @return Current count from the Encoder adjusted for the 1x, 2x, or 4x scale
* factor.
*/
public int get() {
return (int) (getRaw() * decodingScaleFactor());
}
/**
* Reset the Encoder distance to zero. Resets the current count to zero on the
* encoder.
*/
public void reset() {
if (m_counter != null) {
m_counter.reset();
} else {
EncoderJNI.resetEncoder(m_encoder);
}
}
/**
* Returns the period of the most recent pulse. Returns the period of the most
* recent Encoder pulse in seconds. This method compensates for the decoding
* type.
*
* @deprecated Use getRate() in favor of this method. This returns unscaled
* periods and getRate() scales using value from
* setDistancePerPulse().
*
* @return Period in seconds of the most recent pulse.
*/
public double getPeriod() {
double measuredPeriod;
if (m_counter != null) {
measuredPeriod = m_counter.getPeriod() / decodingScaleFactor();
} else {
measuredPeriod = EncoderJNI.getEncoderPeriod(m_encoder);
}
return measuredPeriod;
}
/**
* Sets the maximum period for stopped detection. Sets the value that
* represents the maximum period of the Encoder before it will assume that the
* attached device is stopped. This timeout allows users to determine if the
* wheels or other shaft has stopped rotating. This method compensates for the
* decoding type.
*
*
* @param maxPeriod The maximum time between rising and falling edges before
* the FPGA will report the device stopped. This is expressed in
* seconds.
*/
public void setMaxPeriod(double maxPeriod) {
if (m_counter != null) {
m_counter.setMaxPeriod(maxPeriod * decodingScaleFactor());
} else {
EncoderJNI.setEncoderMaxPeriod(m_encoder, maxPeriod);
}
}
/**
* Determine if the encoder is stopped. Using the MaxPeriod value, a boolean
* is returned that is true if the encoder is considered stopped and false if
* it is still moving. A stopped encoder is one where the most recent pulse
* width exceeds the MaxPeriod.
*
* @return True if the encoder is considered stopped.
*/
public boolean getStopped() {
if (m_counter != null) {
return m_counter.getStopped();
} else {
return EncoderJNI.getEncoderStopped(m_encoder);
}
}
/**
* The last direction the encoder value changed.
*
* @return The last direction the encoder value changed.
*/
public boolean getDirection() {
if (m_counter != null) {
return m_counter.getDirection();
} else {
return EncoderJNI.getEncoderDirection(m_encoder);
}
}
/**
* The scale needed to convert a raw counter value into a number of encoder
* pulses.
*/
private double decodingScaleFactor() {
switch (m_encodingType) {
case k1X:
return 1.0;
case k2X:
return 0.5;
case k4X:
return 0.25;
default:
// This is never reached, EncodingType enum limits values
return 0.0;
}
}
/**
* Get the distance the robot has driven since the last reset.
*
* @return The distance driven since the last reset as scaled by the value
* from setDistancePerPulse().
*/
public double getDistance() {
return getRaw() * decodingScaleFactor() * m_distancePerPulse;
}
/**
* Get the current rate of the encoder. Units are distance per second as
* scaled by the value from setDistancePerPulse().
*
* @return The current rate of the encoder.
*/
public double getRate() {
return m_distancePerPulse / getPeriod();
}
/**
* Set the minimum rate of the device before the hardware reports it stopped.
*
* @param minRate The minimum rate. The units are in distance per second as
* scaled by the value from setDistancePerPulse().
*/
public void setMinRate(double minRate) {
setMaxPeriod(m_distancePerPulse / minRate);
}
/**
* Set the distance per pulse for this encoder. This sets the multiplier used
* to determine the distance driven based on the count value from the encoder.
* Do not include the decoding type in this scale. The library already
* compensates for the decoding type. Set this value based on the encoder's
* rated Pulses per Revolution and factor in gearing reductions following the
* encoder shaft. This distance can be in any units you like, linear or
* angular.
*
* @param distancePerPulse The scale factor that will be used to convert
* pulses to useful units.
*/
public void setDistancePerPulse(double distancePerPulse) {
m_distancePerPulse = distancePerPulse;
}
/**
* Set the direction sensing for this encoder. This sets the direction sensing
* on the encoder so that it could count in the correct software direction
* regardless of the mounting.
*
* @param reverseDirection true if the encoder direction should be reversed
*/
public void setReverseDirection(boolean reverseDirection) {
if (m_counter != null) {
m_counter.setReverseDirection(reverseDirection);
} else {
}
}
/**
* Set the Samples to Average which specifies the number of samples of the
* timer to average when calculating the period. Perform averaging to account
* for mechanical imperfections or as oversampling to increase resolution.
*
* TODO: Should this throw a checked exception, so that the user has to deal
* with giving an incorrect value?
*
* @param samplesToAverage The number of samples to average from 1 to 127.
*/
public void setSamplesToAverage(int samplesToAverage) {
switch (m_encodingType) {
case k4X:
EncoderJNI.setEncoderSamplesToAverage(m_encoder, samplesToAverage);
break;
case k1X:
case k2X:
m_counter.setSamplesToAverage(samplesToAverage);
break;
}
}
/**
* Get the Samples to Average which specifies the number of samples of the
* timer to average when calculating the period. Perform averaging to account
* for mechanical imperfections or as oversampling to increase resolution.
*
* @return SamplesToAverage The number of samples being averaged (from 1 to
* 127)
*/
public int getSamplesToAverage() {
switch (m_encodingType) {
case k4X:
return EncoderJNI.getEncoderSamplesToAverage(m_encoder);
case k1X:
case k2X:
return m_counter.getSamplesToAverage();
}
return 1;
}
/**
* Set which parameter of the encoder you are using as a process control
* variable. The encoder class supports the rate and distance parameters.
*
* @param pidSource An enum to select the parameter.
*/
public void setPIDSourceType(PIDSourceType pidSource) {
m_pidSource = pidSource;
}
/**
* {@inheritDoc}
*/
public PIDSourceType getPIDSourceType() {
return m_pidSource;
}
/**
* Implement the PIDSource interface.
*
* @return The current value of the selected source parameter.
*/
public double pidGet() {
switch (m_pidSource) {
case kDisplacement:
return getDistance();
case kRate:
return getRate();
default:
return 0.0;
}
}
/**
* Set the index source for the encoder. When this source rises, the encoder
* count automatically resets.
*
* @param channel A DIO channel to set as the encoder index
* @param type The state that will cause the encoder to reset
*/
public void setIndexSource(int channel, IndexingType type) {
boolean activeHigh =
(type == IndexingType.kResetWhileHigh) || (type == IndexingType.kResetOnRisingEdge);
boolean edgeSensitive =
(type == IndexingType.kResetOnFallingEdge) || (type == IndexingType.kResetOnRisingEdge);
EncoderJNI.setEncoderIndexSource(m_encoder, channel, false, activeHigh, edgeSensitive);
}
/**
* Set the index source for the encoder. When this source is activated, the
* encoder count automatically resets.
*
* @param channel A DIO channel to set as the encoder index
*/
public void setIndexSource(int channel) {
this.setIndexSource(channel, IndexingType.kResetOnRisingEdge);
}
/**
* Set the index source for the encoder. When this source rises, the encoder
* count automatically resets.
*
* @param source A digital source to set as the encoder index
* @param type The state that will cause the encoder to reset
*/
public void setIndexSource(DigitalSource source, IndexingType type) {
boolean activeHigh =
(type == IndexingType.kResetWhileHigh) || (type == IndexingType.kResetOnRisingEdge);
boolean edgeSensitive =
(type == IndexingType.kResetOnFallingEdge) || (type == IndexingType.kResetOnRisingEdge);
EncoderJNI.setEncoderIndexSource(m_encoder, source.getChannelForRouting(),
source.getAnalogTriggerForRouting(), activeHigh, edgeSensitive);
}
/**
* Set the index source for the encoder. When this source is activated, the
* encoder count automatically resets.
*
* @param source A digital source to set as the encoder index
*/
public void setIndexSource(DigitalSource source) {
this.setIndexSource(source, IndexingType.kResetOnRisingEdge);
}
/*
* Live Window code, only does anything if live window is activated.
*/
public String getSmartDashboardType() {
switch (m_encodingType) {
case k4X:
return "Quadrature Encoder";
default:
return "Encoder";
}
}
private ITable m_table;
/**
* {@inheritDoc}
*/
public void initTable(ITable subtable) {
m_table = subtable;
updateTable();
}
/**
* {@inheritDoc}
*/
public ITable getTable() {
return m_table;
}
/**
* {@inheritDoc}
*/
public void updateTable() {
if (m_table != null) {
m_table.putNumber("Speed", getRate());
m_table.putNumber("Distance", getDistance());
m_table.putNumber("Distance per Tick", m_distancePerPulse);
}
}
/**
* {@inheritDoc}
*/
public void startLiveWindowMode() {}
/**
* {@inheritDoc}
*/
public void stopLiveWindowMode() {}
}

View File

@@ -0,0 +1,95 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType;
import edu.wpi.first.wpilibj.communication.UsageReporting;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
/**
* Alias for counter class. Implement the gear tooth sensor supplied by FIRST.
* Currently there is no reverse sensing on the gear tooth sensor, but in future
* versions we might implement the necessary timing in the FPGA to sense
* direction.
*/
public class GearTooth extends Counter {
private static final double kGearToothThreshold = 55e-6;
/**
* Common code called by the constructors.
*/
public void enableDirectionSensing(boolean directionSensitive) {
if (directionSensitive) {
setPulseLengthMode(kGearToothThreshold);
}
}
/**
* Construct a GearTooth sensor given a channel.
*
* No direction sensing is assumed.
*
* @param channel The GPIO channel that the sensor is connected to.
*/
public GearTooth(final int channel) {
this(channel, false);
}
/**
* Construct a GearTooth sensor given a channel.
*
* @param channel The DIO channel that the sensor is connected to. 0-9 are
* on-board, 10-25 are on the MXP port
* @param directionSensitive True to enable the pulse length decoding in
* hardware to specify count direction.
*/
public GearTooth(final int channel, boolean directionSensitive) {
super(channel);
enableDirectionSensing(directionSensitive);
if (directionSensitive) {
UsageReporting.report(tResourceType.kResourceType_GearTooth, channel, 0, "D");
} else {
UsageReporting.report(tResourceType.kResourceType_GearTooth, channel, 0);
}
LiveWindow.addSensor("GearTooth", channel, this);
}
/**
* Construct a GearTooth sensor given a digital input. This should be used
* when sharing digital inputs.
*
* @param source An existing DigitalSource object (such as a DigitalInput)
* @param directionSensitive True to enable the pulse length decoding in
* hardware to specify count direction.
*/
public GearTooth(DigitalSource source, boolean directionSensitive) {
super(source);
enableDirectionSensing(directionSensitive);
}
/**
* Construct a GearTooth sensor given a digital input. This should be used
* when sharing digial inputs.
*
* No direction sensing is assumed.
*
* @param source An object that fully descibes the input that the sensor is
* connected to.
*/
public GearTooth(DigitalSource source) {
this(source, false);
}
/*
* Live Window code, only does anything if live window is activated.
*/
public String getSmartDashboardType() {
return "Gear Tooth";
}
}

View File

@@ -0,0 +1,124 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import edu.wpi.first.wpilibj.interfaces.Gyro;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable;
import edu.wpi.first.wpilibj.tables.ITable;
/**
* GyroBase is the common base class for Gyro implementations such as
* AnalogGyro.
*/
public abstract class GyroBase extends SensorBase implements Gyro, PIDSource, LiveWindowSendable {
private PIDSourceType m_pidSource = PIDSourceType.kDisplacement;
/**
* {@inheritDoc}
*/
public abstract void initGyro();
/**
* {@inheritDoc}
*/
public abstract void reset();
/**
* {@inheritDoc}
*/
public abstract double getAngle();
/**
* {@inheritDoc}
*/
public abstract double getRate();
/**
* Set which parameter of the gyro you are using as a process control
* variable. The Gyro class supports the rate and displacement parameters
*
* @param pidSource An enum to select the parameter.
*/
public void setPIDSourceType(PIDSourceType pidSource) {
m_pidSource = pidSource;
}
/**
* {@inheritDoc}
*/
public PIDSourceType getPIDSourceType() {
return m_pidSource;
}
/**
* Get the output of the gyro for use with PIDControllers. May be the angle or
* rate depending on the set PIDSourceType
*
* @return the output according to the gyro
*/
@Override
public double pidGet() {
switch (m_pidSource) {
case kRate:
return getRate();
case kDisplacement:
return getAngle();
default:
return 0.0;
}
}
/*
* Live Window code, only does anything if live window is activated.
*/
@Override
public String getSmartDashboardType() {
return "Gyro";
}
private ITable m_table;
/**
* {@inheritDoc}
*/
@Override
public void initTable(ITable subtable) {
m_table = subtable;
updateTable();
}
/**
* {@inheritDoc}
*/
@Override
public ITable getTable() {
return m_table;
}
/**
* {@inheritDoc}
*/
@Override
public void updateTable() {
if (m_table != null) {
m_table.putNumber("Value", getAngle());
}
}
/**
* {@inheritDoc}
*/
@Override
public void startLiveWindowMode() {}
/**
* {@inheritDoc}
*/
@Override
public void stopLiveWindowMode() {}
}

View File

@@ -0,0 +1,352 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import java.nio.ByteOrder;
import java.nio.ByteBuffer;
import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType;
import edu.wpi.first.wpilibj.communication.UsageReporting;
import edu.wpi.first.wpilibj.hal.HALLibrary;
import edu.wpi.first.wpilibj.hal.I2CJNI;
import edu.wpi.first.wpilibj.util.BoundaryException;
/**
* I2C bus interface class.
*
* This class is intended to be used by sensor (and other I2C device) drivers.
* It probably should not be used directly.
*
*/
public class I2C extends SensorBase {
public enum Port {
kOnboard(0), kMXP(1);
private int value;
private Port(int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
};
private Port m_port;
private int m_deviceAddress;
/**
* Constructor.
*
* @param port The I2C port the device is connected to.
* @param deviceAddress The address of the device on the I2C bus.
*/
public I2C(Port port, int deviceAddress) {
m_port = port;
m_deviceAddress = deviceAddress;
I2CJNI.i2CInitialize((byte) m_port.getValue());
UsageReporting.report(tResourceType.kResourceType_I2C, deviceAddress);
}
/**
* Destructor.
*/
public void free() {}
/**
* Generic transaction.
*
* This is a lower-level interface to the I2C hardware giving you more control
* over each transaction.
*
* @param dataToSend Buffer of data to send as part of the transaction.
* @param sendSize Number of bytes to send as part of the transaction.
* @param dataReceived Buffer to read data into.
* @param receiveSize Number of bytes to read from the device.
* @return Transfer Aborted... false for success, true for aborted.
*/
public synchronized boolean transaction(byte[] dataToSend, int sendSize, byte[] dataReceived,
int receiveSize) {
boolean aborted = true;
ByteBuffer dataToSendBuffer = ByteBuffer.allocateDirect(sendSize);
dataToSendBuffer.put(dataToSend);
ByteBuffer dataReceivedBuffer = ByteBuffer.allocateDirect(receiveSize);
aborted =
I2CJNI.i2CTransaction((byte) m_port.getValue(), (byte) m_deviceAddress, dataToSendBuffer,
(byte) sendSize, dataReceivedBuffer, (byte) receiveSize) != 0;
if (receiveSize > 0 && dataReceived != null) {
dataReceivedBuffer.get(dataReceived);
}
return aborted;
}
/**
* Generic transaction.
*
* This is a lower-level interface to the I2C hardware giving you more control
* over each transaction.
*
* @param dataToSend Buffer of data to send as part of the transaction. Must
* be allocated using ByteBuffer.allocateDirect().
* @param sendSize Number of bytes to send as part of the transaction.
* @param dataReceived Buffer to read data into. Must be allocated using
* ByteBuffer.allocateDirect().
* @param receiveSize Number of bytes to read from the device.
* @return Transfer Aborted... false for success, true for aborted.
*/
public synchronized boolean transaction(ByteBuffer dataToSend, int sendSize, ByteBuffer dataReceived,
int receiveSize) {
boolean aborted = true;
if (!dataToSend.isDirect())
throw new IllegalArgumentException("dataToSend must be a direct buffer");
if (dataToSend.capacity() < sendSize)
throw new IllegalArgumentException("dataToSend is too small, must be at least " + sendSize);
if (!dataReceived.isDirect())
throw new IllegalArgumentException("dataReceived must be a direct buffer");
if (dataReceived.capacity() < receiveSize)
throw new IllegalArgumentException("dataReceived is too small, must be at least " + receiveSize);
return I2CJNI.i2CTransaction((byte) m_port.getValue(), (byte) m_deviceAddress, dataToSend, (byte) sendSize, dataReceived, (byte) receiveSize) != 0;
}
/**
* Attempt to address a device on the I2C bus.
*
* This allows you to figure out if there is a device on the I2C bus that
* responds to the address specified in the constructor.
*
* @return Transfer Aborted... false for success, true for aborted.
*/
public boolean addressOnly() {
return transaction((byte[]) null, (byte) 0, (byte[]) null, (byte) 0);
}
/**
* Execute a write transaction with the device.
*
* Write a single byte to a register on a device and wait until the
* transaction is complete.
*
* @param registerAddress The address of the register on the device to be
* written.
* @param data The byte to write to the register on the device.
*/
public synchronized boolean write(int registerAddress, int data) {
byte[] buffer = new byte[2];
buffer[0] = (byte) registerAddress;
buffer[1] = (byte) data;
ByteBuffer dataToSendBuffer = ByteBuffer.allocateDirect(2);
dataToSendBuffer.put(buffer);
return I2CJNI.i2CWrite((byte) m_port.getValue(), (byte) m_deviceAddress, dataToSendBuffer,
(byte) buffer.length) < 0;
}
/**
* Execute a write transaction with the device.
*
* Write multiple bytes to a register on a device and wait until the
* transaction is complete.
*
* @param data The data to write to the device.
*/
public synchronized boolean writeBulk(byte[] data) {
ByteBuffer dataToSendBuffer = ByteBuffer.allocateDirect(data.length);
dataToSendBuffer.put(data);
return I2CJNI.i2CWrite((byte) m_port.getValue(), (byte) m_deviceAddress, dataToSendBuffer,
(byte) data.length) < 0;
}
/**
* Execute a write transaction with the device.
*
* Write multiple bytes to a register on a device and wait until the
* transaction is complete.
*
* @param data The data to write to the device. Must be created using
* ByteBuffer.allocateDirect().
*/
public synchronized boolean writeBulk(ByteBuffer data, int size) {
if (!data.isDirect())
throw new IllegalArgumentException("must be a direct buffer");
if (data.capacity() < size)
throw new IllegalArgumentException("buffer is too small, must be at least " + size);
return I2CJNI.i2CWrite((byte) m_port.getValue(), (byte) m_deviceAddress, data,
(byte) size) < 0;
}
/**
* Execute a read transaction with the device.
*
* Read bytes from a device. Most I2C devices will auto-increment the
* register pointer internally allowing you to read consecutive
* registers on a device in a single transaction.
*
* @param registerAddress The register to read first in the transaction.
* @param count The number of bytes to read in the transaction.
* @param buffer A pointer to the array of bytes to store the data read from
* the device.
* @return Transfer Aborted... false for success, true for aborted.
*/
public boolean read(int registerAddress, int count, byte[] buffer) {
if (count < 1) {
throw new BoundaryException("Value must be at least 1, " + count +
" given");
}
if (buffer == null) {
throw new NullPointerException("Null return buffer was given");
}
byte[] registerAddressArray = new byte[1];
registerAddressArray[0] = (byte) registerAddress;
return transaction(registerAddressArray, registerAddressArray.length, buffer, count);
}
/**
* Execute a read transaction with the device.
*
* Read bytes from a device. Most I2C devices will auto-increment the
* register pointer internally allowing you to read consecutive
* registers on a device in a single transaction.
*
* @param registerAddress The register to read first in the transaction.
* @param count The number of bytes to read in the transaction.
* @param buffer A buffer to store the data read from the device. Must be
* created using ByteBuffer.allocateDirect().
* @return Transfer Aborted... false for success, true for aborted.
*/
public boolean read(int registerAddress, int count, ByteBuffer buffer) {
if (count < 1) {
throw new BoundaryException("Value must be at least 1, " + count +
" given");
}
if (!buffer.isDirect())
throw new IllegalArgumentException("must be a direct buffer");
if (buffer.capacity() < count)
throw new IllegalArgumentException("buffer is too small, must be at least " + count);
ByteBuffer dataToSendBuffer = ByteBuffer.allocateDirect(1);
dataToSendBuffer.put(0, (byte) registerAddress);
return transaction(dataToSendBuffer, 1, buffer, count);
}
/**
* Execute a read only transaction with the device.
*
* Read bytes from a device. This method does not write any data to prompt
* the device.
*
* @param buffer A pointer to the array of bytes to store the data read from
* the device.
* @param count The number of bytes to read in the transaction.
* @return Transfer Aborted... false for success, true for aborted.
*/
public boolean readOnly(byte[] buffer, int count) {
if (count < 1) {
throw new BoundaryException("Value must be at least 1, " + count +
" given");
}
if (buffer == null) {
throw new NullPointerException("Null return buffer was given");
}
ByteBuffer dataReceivedBuffer = ByteBuffer.allocateDirect(count);
int retVal =
I2CJNI.i2CRead((byte) m_port.getValue(), (byte) m_deviceAddress, dataReceivedBuffer,
(byte) count);
dataReceivedBuffer.get(buffer);
return retVal < 0;
}
/**
* Execute a read only transaction with the device.
*
* Read bytes from a device. This method does not write any data to prompt
* the device.
*
* @param buffer A pointer to the array of bytes to store the data read from
* the device. Must be created using ByteBuffer.allocateDirect().
* @param count The number of bytes to read in the transaction.
* @return Transfer Aborted... false for success, true for aborted.
*/
public boolean readOnly(ByteBuffer buffer, int count) {
if (count < 1) {
throw new BoundaryException("Value must be at least 1, " + count +
" given");
}
if (!buffer.isDirect())
throw new IllegalArgumentException("must be a direct buffer");
if (buffer.capacity() < count)
throw new IllegalArgumentException("buffer is too small, must be at least " + count);
return I2CJNI.i2CRead((byte) m_port.getValue(), (byte) m_deviceAddress, buffer,
(byte) count) < 0;
}
/**
* Send a broadcast write to all devices on the I2C bus.
*
* This is not currently implemented!
*
* @param registerAddress The register to write on all devices on the bus.
* @param data The value to write to the devices.
*/
public void broadcast(int registerAddress, int data) {}
/**
* Verify that a device's registers contain expected values.
*
* Most devices will have a set of registers that contain a known value that
* can be used to identify them. This allows an I2C device driver to easily
* verify that the device contains the expected value.
*
* @pre The device must support and be configured to use register
* auto-increment.
*
* @param registerAddress The base register to start reading from the device.
* @param count The size of the field to be verified.
* @param expected A buffer containing the values expected from the device.
* @return true if the sensor was verified to be connected
*/
public boolean verifySensor(int registerAddress, int count, byte[] expected) {
// TODO: Make use of all 7 read bytes
ByteBuffer dataToSendBuffer = ByteBuffer.allocateDirect(1);
ByteBuffer deviceData = ByteBuffer.allocateDirect(4);
for (int i = 0, curRegisterAddress = registerAddress; i < count; i += 4, curRegisterAddress +=
4) {
int toRead = count - i < 4 ? count - i : 4;
// Read the chunk of data. Return false if the sensor does not
// respond.
dataToSendBuffer.put(0, (byte) curRegisterAddress);
if (transaction(dataToSendBuffer, 1, deviceData, toRead)) {
return false;
}
for (byte j = 0; j < toRead; j++) {
if (deviceData.get(j) != expected[i + j]) {
return false;
}
}
}
return true;
}
}

View File

@@ -0,0 +1,62 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import edu.wpi.first.wpilibj.hal.InterruptJNI.InterruptJNIHandlerFunction;
/**
* It is recommended that you use this class in conjunction with classes from
* {@link java.util.concurrent.atomic} as these objects are all thread safe.
*$
* @author Jonathan Leitschuh
*
* @param <T> The type of the parameter that should be returned to the the
* method {@link #interruptFired(int, Object)}
*/
public abstract class InterruptHandlerFunction<T> {
/**
* The entry point for the interrupt. When the interrupt fires the
* {@link #apply(int, Object)} method is called. The outer class is provided
* as an interface to allow the implementer to pass a generic object to the
* interrupt fired method.
*$
* @author Jonathan Leitschuh
*/
private class Function implements InterruptJNIHandlerFunction {
@SuppressWarnings("unchecked")
@Override
public void apply(int interruptAssertedMask, Object param) {
interruptFired(interruptAssertedMask, (T) param);
}
}
final Function function = new Function();
/**
* This method is run every time an interrupt is fired.
*$
* @param interruptAssertedMask
* @param param The parameter provided by overriding the
* {@link #overridableParameter()} method.
*/
public abstract void interruptFired(int interruptAssertedMask, T param);
/**
* Override this method if you would like to pass a specific parameter to the
* {@link #interruptFired(int, Object)} when it is fired by the interrupt.
* This method is called once when
* {@link InterruptableSensorBase#requestInterrupts(InterruptHandlerFunction)}
* is run.
*$
* @return The object that should be passed to the interrupt when it runs
*/
public T overridableParameter() {
return null;
}
}

View File

@@ -0,0 +1,231 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import edu.wpi.first.wpilibj.hal.InterruptJNI;
import edu.wpi.first.wpilibj.util.AllocationException;
import edu.wpi.first.wpilibj.util.CheckedAllocationException;
/**
* Base for sensors to be used with interrupts
*/
public abstract class InterruptableSensorBase extends SensorBase {
/**
* The interrupt resource
*/
protected long m_interrupt = 0;
/**
* Flags if the interrupt being allocated is synchronous
*/
protected boolean m_isSynchronousInterrupt = false;
/**
* The index of the interrupt
*/
protected int m_interruptIndex;
/**
* Resource manager
*/
protected static Resource interrupts = new Resource(8);
/**
* Create a new InterrupatableSensorBase
*/
public InterruptableSensorBase() {
m_interrupt = 0;
}
/**
* @return true if this is an analog trigger
*/
abstract boolean getAnalogTriggerForRouting();
/**
* @return channel routing number
*/
abstract int getChannelForRouting();
/**
* @return module routing number
*/
abstract byte getModuleForRouting();
/**
* Request one of the 8 interrupts asynchronously on this digital input.
*
* @param handler The {@link InterruptHandlerFunction} that contains the
* method {@link InterruptHandlerFunction#interruptFired(int, Object)}
* that will be called whenever there is an interrupt on this device.
* Request interrupts in synchronous mode where the user program
* interrupt handler will be called when an interrupt occurs. The
* default is interrupt on rising edges only.
*/
public void requestInterrupts(InterruptHandlerFunction<?> handler) {
if (m_interrupt != 0) {
throw new AllocationException("The interrupt has already been allocated");
}
allocateInterrupts(false);
assert (m_interrupt != 0);
InterruptJNI.requestInterrupts(m_interrupt, getModuleForRouting(), getChannelForRouting(),
getAnalogTriggerForRouting());
setUpSourceEdge(true, false);
InterruptJNI.attachInterruptHandler(m_interrupt, handler.function,
handler.overridableParameter());
}
/**
* Request one of the 8 interrupts synchronously on this digital input.
* Request interrupts in synchronous mode where the user program will have to
* explicitly wait for the interrupt to occur using {@link #waitForInterrupt}.
* The default is interrupt on rising edges only.
*/
public void requestInterrupts() {
if (m_interrupt != 0) {
throw new AllocationException("The interrupt has already been allocated");
}
allocateInterrupts(true);
assert (m_interrupt != 0);
InterruptJNI.requestInterrupts(m_interrupt, getModuleForRouting(), getChannelForRouting(),
getAnalogTriggerForRouting());
setUpSourceEdge(true, false);
}
/**
* Allocate the interrupt
*
* @param watcher true if the interrupt should be in synchronous mode where
* the user program will have to explicitly wait for the interrupt to
* occur.
*/
protected void allocateInterrupts(boolean watcher) {
try {
m_interruptIndex = interrupts.allocate();
} catch (CheckedAllocationException e) {
throw new AllocationException("No interrupts are left to be allocated");
}
m_isSynchronousInterrupt = watcher;
m_interrupt =
InterruptJNI.initializeInterrupts(m_interruptIndex, watcher);
}
/**
* Cancel interrupts on this device. This deallocates all the chipobject
* structures and disables any interrupts.
*/
public void cancelInterrupts() {
if (m_interrupt == 0) {
throw new IllegalStateException("The interrupt is not allocated.");
}
InterruptJNI.cleanInterrupts(m_interrupt);
m_interrupt = 0;
interrupts.free(m_interruptIndex);
}
/**
* In synchronous mode, wait for the defined interrupt to occur.
*
* @param timeout Timeout in seconds
* @param ignorePrevious If true, ignore interrupts that happened before
* waitForInterrupt was called.
*/
public void waitForInterrupt(double timeout, boolean ignorePrevious) {
if (m_interrupt == 0) {
throw new IllegalStateException("The interrupt is not allocated.");
}
InterruptJNI.waitForInterrupt(m_interrupt, timeout, ignorePrevious);
}
/**
* In synchronous mode, wait for the defined interrupt to occur.
*
* @param timeout Timeout in seconds
*/
public void waitForInterrupt(double timeout) {
waitForInterrupt(timeout, true);
}
/**
* Enable interrupts to occur on this input. Interrupts are disabled when the
* RequestInterrupt call is made. This gives time to do the setup of the other
* options before starting to field interrupts.
*/
public void enableInterrupts() {
if (m_interrupt == 0) {
throw new IllegalStateException("The interrupt is not allocated.");
}
if (m_isSynchronousInterrupt) {
throw new IllegalStateException("You do not need to enable synchronous interrupts");
}
InterruptJNI.enableInterrupts(m_interrupt);
}
/**
* Disable Interrupts without without deallocating structures.
*/
public void disableInterrupts() {
if (m_interrupt == 0) {
throw new IllegalStateException("The interrupt is not allocated.");
}
if (m_isSynchronousInterrupt) {
throw new IllegalStateException("You can not disable synchronous interrupts");
}
InterruptJNI.disableInterrupts(m_interrupt);
}
/**
* Return the timestamp for the rising interrupt that occurred most recently.
* This is in the same time domain as getClock(). The rising-edge interrupt
* should be enabled with {@link #setUpSourceEdge}
*$
* @return Timestamp in seconds since boot.
*/
public double readRisingTimestamp() {
if (m_interrupt == 0) {
throw new IllegalStateException("The interrupt is not allocated.");
}
return InterruptJNI.readRisingTimestamp(m_interrupt);
}
/**
* Return the timestamp for the falling interrupt that occurred most recently.
* This is in the same time domain as getClock(). The falling-edge interrupt
* should be enabled with {@link #setUpSourceEdge}
*$
* @return Timestamp in seconds since boot.
*/
public double readFallingTimestamp() {
if (m_interrupt == 0) {
throw new IllegalStateException("The interrupt is not allocated.");
}
return InterruptJNI.readFallingTimestamp(m_interrupt);
}
/**
* Set which edge to trigger interrupts on
*
* @param risingEdge true to interrupt on rising edge
* @param fallingEdge true to interrupt on falling edge
*/
public void setUpSourceEdge(boolean risingEdge, boolean fallingEdge) {
if (m_interrupt != 0) {
InterruptJNI.setInterruptUpSourceEdge(m_interrupt, risingEdge,
fallingEdge);
} else {
throw new IllegalArgumentException("You must call RequestInterrupts before setUpSourceEdge");
}
}
}

View File

@@ -0,0 +1,280 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary;
import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tInstances;
import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType;
import edu.wpi.first.wpilibj.communication.UsageReporting;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
/**
* IterativeRobot implements a specific type of Robot Program framework,
* extending the RobotBase class.
*
* The IterativeRobot class is intended to be subclassed by a user creating a
* robot program.
*
* This class is intended to implement the "old style" default code, by
* providing the following functions which are called by the main loop,
* startCompetition(), at the appropriate times:
*
* robotInit() -- provide for initialization at robot power-on
*
* init() functions -- each of the following functions is called once when the
* appropriate mode is entered: - DisabledInit() -- called only when first
* disabled - AutonomousInit() -- called each and every time autonomous is
* entered from another mode - TeleopInit() -- called each and every time teleop
* is entered from another mode - TestInit() -- called each and every time test
* mode is entered from anothermode
*
* Periodic() functions -- each of these functions is called iteratively at the
* appropriate periodic rate (aka the "slow loop"). The period of the iterative
* robot is synced to the driver station control packets, giving a periodic
* frequency of about 50Hz (50 times per second). - disabledPeriodic() -
* autonomousPeriodic() - teleopPeriodic() - testPeriodoc()
*
*/
public class IterativeRobot extends RobotBase {
private boolean m_disabledInitialized;
private boolean m_autonomousInitialized;
private boolean m_teleopInitialized;
private boolean m_testInitialized;
/**
* Constructor for RobotIterativeBase
*
* The constructor initializes the instance variables for the robot to
* indicate the status of initialization for disabled, autonomous, and teleop
* code.
*/
public IterativeRobot() {
// set status for initialization of disabled, autonomous, and teleop code.
m_disabledInitialized = false;
m_autonomousInitialized = false;
m_teleopInitialized = false;
m_testInitialized = false;
}
/**
* Provide an alternate "main loop" via startCompetition().
*
*/
public void startCompetition() {
UsageReporting.report(tResourceType.kResourceType_Framework, tInstances.kFramework_Iterative);
robotInit();
// Tell the DS that the robot is ready to be enabled
FRCNetworkCommunicationsLibrary.FRCNetworkCommunicationObserveUserProgramStarting();
// loop forever, calling the appropriate mode-dependent function
LiveWindow.setEnabled(false);
while (true) {
// Call the appropriate function depending upon the current robot mode
if (isDisabled()) {
// call DisabledInit() if we are now just entering disabled mode from
// either a different mode or from power-on
if (!m_disabledInitialized) {
LiveWindow.setEnabled(false);
disabledInit();
m_disabledInitialized = true;
// reset the initialization flags for the other modes
m_autonomousInitialized = false;
m_teleopInitialized = false;
m_testInitialized = false;
}
if (nextPeriodReady()) {
FRCNetworkCommunicationsLibrary.FRCNetworkCommunicationObserveUserProgramDisabled();
disabledPeriodic();
}
} else if (isTest()) {
// call TestInit() if we are now just entering test mode from either
// a different mode or from power-on
if (!m_testInitialized) {
LiveWindow.setEnabled(true);
testInit();
m_testInitialized = true;
m_autonomousInitialized = false;
m_teleopInitialized = false;
m_disabledInitialized = false;
}
if (nextPeriodReady()) {
FRCNetworkCommunicationsLibrary.FRCNetworkCommunicationObserveUserProgramTest();
testPeriodic();
}
} else if (isAutonomous()) {
// call Autonomous_Init() if this is the first time
// we've entered autonomous_mode
if (!m_autonomousInitialized) {
LiveWindow.setEnabled(false);
// KBS NOTE: old code reset all PWMs and relays to "safe values"
// whenever entering autonomous mode, before calling
// "Autonomous_Init()"
autonomousInit();
m_autonomousInitialized = true;
m_testInitialized = false;
m_teleopInitialized = false;
m_disabledInitialized = false;
}
if (nextPeriodReady()) {
FRCNetworkCommunicationsLibrary.FRCNetworkCommunicationObserveUserProgramAutonomous();
autonomousPeriodic();
}
} else {
// call Teleop_Init() if this is the first time
// we've entered teleop_mode
if (!m_teleopInitialized) {
LiveWindow.setEnabled(false);
teleopInit();
m_teleopInitialized = true;
m_testInitialized = false;
m_autonomousInitialized = false;
m_disabledInitialized = false;
}
if (nextPeriodReady()) {
FRCNetworkCommunicationsLibrary.FRCNetworkCommunicationObserveUserProgramTeleop();
teleopPeriodic();
}
}
m_ds.waitForData();
}
}
/**
* Determine if the appropriate next periodic function should be called. Call
* the periodic functions whenever a packet is received from the Driver
* Station, or about every 20ms.
*/
private boolean nextPeriodReady() {
return m_ds.isNewControlData();
}
/* ----------- Overridable initialization code ----------------- */
/**
* Robot-wide initialization code should go here.
*
* Users should override this method for default Robot-wide initialization
* which will be called when the robot is first powered on. It will be called
* exactly one time.
*
* Warning: the Driver Station "Robot Code" light and FMS "Robot Ready"
* indicators will be off until RobotInit() exits. Code in RobotInit() that
* waits for enable will cause the robot to never indicate that the code is
* ready, causing the robot to be bypassed in a match.
*/
public void robotInit() {
System.out.println("Default IterativeRobot.robotInit() method... Overload me!");
}
/**
* Initialization code for disabled mode should go here.
*
* Users should override this method for initialization code which will be
* called each time the robot enters disabled mode.
*/
public void disabledInit() {
System.out.println("Default IterativeRobot.disabledInit() method... Overload me!");
}
/**
* Initialization code for autonomous mode should go here.
*
* Users should override this method for initialization code which will be
* called each time the robot enters autonomous mode.
*/
public void autonomousInit() {
System.out.println("Default IterativeRobot.autonomousInit() method... Overload me!");
}
/**
* Initialization code for teleop mode should go here.
*
* Users should override this method for initialization code which will be
* called each time the robot enters teleop mode.
*/
public void teleopInit() {
System.out.println("Default IterativeRobot.teleopInit() method... Overload me!");
}
/**
* Initialization code for test mode should go here.
*
* Users should override this method for initialization code which will be
* called each time the robot enters test mode.
*/
public void testInit() {
System.out.println("Default IterativeRobot.testInit() method... Overload me!");
}
/* ----------- Overridable periodic code ----------------- */
private boolean dpFirstRun = true;
/**
* Periodic code for disabled mode should go here.
*
* Users should override this method for code which will be called
* periodically at a regular rate while the robot is in disabled mode.
*/
public void disabledPeriodic() {
if (dpFirstRun) {
System.out.println("Default IterativeRobot.disabledPeriodic() method... Overload me!");
dpFirstRun = false;
}
Timer.delay(0.001);
}
private boolean apFirstRun = true;
/**
* Periodic code for autonomous mode should go here.
*
* Users should override this method for code which will be called
* periodically at a regular rate while the robot is in autonomous mode.
*/
public void autonomousPeriodic() {
if (apFirstRun) {
System.out.println("Default IterativeRobot.autonomousPeriodic() method... Overload me!");
apFirstRun = false;
}
Timer.delay(0.001);
}
private boolean tpFirstRun = true;
/**
* Periodic code for teleop mode should go here.
*
* Users should override this method for code which will be called
* periodically at a regular rate while the robot is in teleop mode.
*/
public void teleopPeriodic() {
if (tpFirstRun) {
System.out.println("Default IterativeRobot.teleopPeriodic() method... Overload me!");
tpFirstRun = false;
}
Timer.delay(0.001);
}
private boolean tmpFirstRun = true;
/**
* Periodic code for test mode should go here
*
* Users should override this method for code which will be called
* periodically at a regular rate while the robot is in test mode.
*/
public void testPeriodic() {
if (tmpFirstRun) {
System.out.println("Default IterativeRobot.testPeriodic() method... Overload me!");
tmpFirstRun = false;
}
}
}

View File

@@ -0,0 +1,127 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType;
import edu.wpi.first.wpilibj.communication.UsageReporting;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
/**
* Texas Instruments / Vex Robotics Jaguar Speed Controller as a PWM device.
*$
* @see CANJaguar CANJaguar for CAN control
*/
public class Jaguar extends SafePWM implements SpeedController {
private boolean isInverted = false;
/**
* Common initialization code called by all constructors.
*/
private void initJaguar() {
/*
* Input profile defined by Luminary Micro.
*$
* Full reverse ranges from 0.671325ms to 0.6972211ms Proportional reverse
* ranges from 0.6972211ms to 1.4482078ms Neutral ranges from 1.4482078ms to
* 1.5517922ms Proportional forward ranges from 1.5517922ms to 2.3027789ms
* Full forward ranges from 2.3027789ms to 2.328675ms
*/
setBounds(2.31, 1.55, 1.507, 1.454, .697);
setPeriodMultiplier(PeriodMultiplier.k1X);
setRaw(m_centerPwm);
setZeroLatch();
UsageReporting.report(tResourceType.kResourceType_Jaguar, getChannel());
LiveWindow.addActuator("Jaguar", getChannel(), this);
}
/**
* Constructor.
*
* @param channel The PWM channel that the Jaguar is attached to. 0-9 are
* on-board, 10-19 are on the MXP port
*/
public Jaguar(final int channel) {
super(channel);
initJaguar();
}
/**
* Set the PWM value.
*
* @deprecated For compatibility with CANJaguar
*
* The PWM value is set using a range of -1.0 to 1.0,
* appropriately scaling the value for the FPGA.
*
* @param speed The speed to set. Value should be between -1.0 and 1.0.
* @param syncGroup The update group to add this Set() to, pending
* UpdateSyncGroup(). If 0, update immediately.
*/
@Deprecated
@Override
public void set(double speed, byte syncGroup) {
setSpeed(isInverted ? -speed : speed);
Feed();
}
/**
* Set the PWM value.
*
* The PWM value is set using a range of -1.0 to 1.0, appropriately scaling
* the value for the FPGA.
*
* @param speed The speed value between -1.0 and 1.0 to set.
*/
@Override
public void set(double speed) {
setSpeed(isInverted ? -speed : speed);
Feed();
}
/**
* Common interface for inverting direction of a speed controller.
*
* @param isInverted The state of inversion, true is inverted.
*/
@Override
public void setInverted(boolean isInverted) {
this.isInverted = isInverted;
}
/**
* Common interface for the inverting direction of a speed controller.
*
* @return isInverted The state of inversion, true is inverted.
*
*/
@Override
public boolean getInverted() {
return this.isInverted;
}
/**
* Get the recently set value of the PWM.
*
* @return The most recently set value for the PWM between -1.0 and 1.0.
*/
@Override
public double get() {
return getSpeed();
}
/**
* Write out the PID value as seen in the PIDOutput base object.
*
* @param output Write out the PWM value as was found in the PIDController
*/
@Override
public void pidWrite(double output) {
set(output);
}
}

View File

@@ -0,0 +1,493 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType;
import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary;
import edu.wpi.first.wpilibj.communication.UsageReporting;
/**
* Handle input from standard Joysticks connected to the Driver Station. This
* class handles standard input that comes from the Driver Station. Each time a
* value is requested the most recent value is returned. There is a single class
* instance for each joystick and the mapping of ports to hardware buttons
* depends on the code in the driver station.
*/
public class Joystick extends GenericHID {
static final byte kDefaultXAxis = 0;
static final byte kDefaultYAxis = 1;
static final byte kDefaultZAxis = 2;
static final byte kDefaultTwistAxis = 2;
static final byte kDefaultThrottleAxis = 3;
static final int kDefaultTriggerButton = 1;
static final int kDefaultTopButton = 2;
/**
* Represents an analog axis on a joystick.
*/
public static class AxisType {
/**
* The integer value representing this enumeration
*/
public final int value;
static final int kX_val = 0;
static final int kY_val = 1;
static final int kZ_val = 2;
static final int kTwist_val = 3;
static final int kThrottle_val = 4;
static final int kNumAxis_val = 5;
/**
* axis: x-axis
*/
public static final AxisType kX = new AxisType(kX_val);
/**
* axis: y-axis
*/
public static final AxisType kY = new AxisType(kY_val);
/**
* axis: z-axis
*/
public static final AxisType kZ = new AxisType(kZ_val);
/**
* axis: twist
*/
public static final AxisType kTwist = new AxisType(kTwist_val);
/**
* axis: throttle
*/
public static final AxisType kThrottle = new AxisType(kThrottle_val);
/**
* axis: number of axis
*/
public static final AxisType kNumAxis = new AxisType(kNumAxis_val);
private AxisType(int value) {
this.value = value;
}
}
/**
* Represents a digital button on the JoyStick
*/
public static class ButtonType {
/**
* The integer value representing this enumeration
*/
public final int value;
static final int kTrigger_val = 0;
static final int kTop_val = 1;
static final int kNumButton_val = 2;
/**
* button: trigger
*/
public static final ButtonType kTrigger = new ButtonType((kTrigger_val));
/**
* button: top button
*/
public static final ButtonType kTop = new ButtonType(kTop_val);
/**
* button: num button types
*/
public static final ButtonType kNumButton = new ButtonType((kNumButton_val));
private ButtonType(int value) {
this.value = value;
}
}
/**
* Represents a rumble output on the JoyStick
*/
public static class RumbleType {
/**
* The integer value representing this enumeration
*/
public final int value;
static final int kLeftRumble_val = 0;
static final int kRightRumble_val = 1;
/**
* Left Rumble
*/
public static final RumbleType kLeftRumble = new RumbleType((kLeftRumble_val));
/**
* Right Rumble
*/
public static final RumbleType kRightRumble = new RumbleType(kRightRumble_val);
private RumbleType(int value) {
this.value = value;
}
}
private DriverStation m_ds;
private final int m_port;
private final byte[] m_axes;
private final byte[] m_buttons;
private int m_outputs;
private short m_leftRumble;
private short m_rightRumble;
/**
* Construct an instance of a joystick. The joystick index is the usb port on
* the drivers station.
*
* @param port The port on the driver station that the joystick is plugged
* into.
*/
public Joystick(final int port) {
this(port, AxisType.kNumAxis.value, ButtonType.kNumButton.value);
m_axes[AxisType.kX.value] = kDefaultXAxis;
m_axes[AxisType.kY.value] = kDefaultYAxis;
m_axes[AxisType.kZ.value] = kDefaultZAxis;
m_axes[AxisType.kTwist.value] = kDefaultTwistAxis;
m_axes[AxisType.kThrottle.value] = kDefaultThrottleAxis;
m_buttons[ButtonType.kTrigger.value] = kDefaultTriggerButton;
m_buttons[ButtonType.kTop.value] = kDefaultTopButton;
UsageReporting.report(tResourceType.kResourceType_Joystick, port);
}
/**
* Protected version of the constructor to be called by sub-classes.
*
* This constructor allows the subclass to configure the number of constants
* for axes and buttons.
*
* @param port The port on the driver station that the joystick is plugged
* into.
* @param numAxisTypes The number of axis types in the enum.
* @param numButtonTypes The number of button types in the enum.
*/
protected Joystick(int port, int numAxisTypes, int numButtonTypes) {
m_ds = DriverStation.getInstance();
m_axes = new byte[numAxisTypes];
m_buttons = new byte[numButtonTypes];
m_port = port;
}
/**
* Get the X value of the joystick. This depends on the mapping of the
* joystick connected to the current port.
*
* @param hand Unused
* @return The X value of the joystick.
*/
public double getX(Hand hand) {
return getRawAxis(m_axes[AxisType.kX.value]);
}
/**
* Get the Y value of the joystick. This depends on the mapping of the
* joystick connected to the current port.
*
* @param hand Unused
* @return The Y value of the joystick.
*/
public double getY(Hand hand) {
return getRawAxis(m_axes[AxisType.kY.value]);
}
/**
* Get the Z value of the joystick. This depends on the mapping of the
* joystick connected to the current port.
*
* @param hand Unused
* @return The Z value of the joystick.
*/
public double getZ(Hand hand) {
return getRawAxis(m_axes[AxisType.kZ.value]);
}
/**
* Get the twist value of the current joystick. This depends on the mapping of
* the joystick connected to the current port.
*
* @return The Twist value of the joystick.
*/
public double getTwist() {
return getRawAxis(m_axes[AxisType.kTwist.value]);
}
/**
* Get the throttle value of the current joystick. This depends on the mapping
* of the joystick connected to the current port.
*
* @return The Throttle value of the joystick.
*/
public double getThrottle() {
return getRawAxis(m_axes[AxisType.kThrottle.value]);
}
/**
* Get the value of the axis.
*
* @param axis The axis to read, starting at 0.
* @return The value of the axis.
*/
public double getRawAxis(final int axis) {
return m_ds.getStickAxis(m_port, axis);
}
/**
* For the current joystick, return the axis determined by the argument.
*
* This is for cases where the joystick axis is returned programatically,
* otherwise one of the previous functions would be preferable (for example
* getX()).
*
* @param axis The axis to read.
* @return The value of the axis.
*/
public double getAxis(final AxisType axis) {
switch (axis.value) {
case AxisType.kX_val:
return getX();
case AxisType.kY_val:
return getY();
case AxisType.kZ_val:
return getZ();
case AxisType.kTwist_val:
return getTwist();
case AxisType.kThrottle_val:
return getThrottle();
default:
return 0.0;
}
}
/**
* For the current joystick, return the number of axis
*/
public int getAxisCount() {
return m_ds.getStickAxisCount(m_port);
}
/**
* Read the state of the trigger on the joystick.
*
* Look up which button has been assigned to the trigger and read its state.
*
* @param hand This parameter is ignored for the Joystick class and is only
* here to complete the GenericHID interface.
* @return The state of the trigger.
*/
public boolean getTrigger(Hand hand) {
return getRawButton(m_buttons[ButtonType.kTrigger.value]);
}
/**
* Read the state of the top button on the joystick.
*
* Look up which button has been assigned to the top and read its state.
*
* @param hand This parameter is ignored for the Joystick class and is only
* here to complete the GenericHID interface.
* @return The state of the top button.
*/
public boolean getTop(Hand hand) {
return getRawButton(m_buttons[ButtonType.kTop.value]);
}
/**
* This is not supported for the Joystick. This method is only here to
* complete the GenericHID interface.
*
* @param hand This parameter is ignored for the Joystick class and is only
* here to complete the GenericHID interface.
* @return The state of the bumper (always false)
*/
public boolean getBumper(Hand hand) {
return false;
}
/**
* Get the button value (starting at button 1)
*
* The appropriate button is returned as a boolean value.
*
* @param button The button number to be read (starting at 1).
* @return The state of the button.
*/
public boolean getRawButton(final int button) {
return m_ds.getStickButton(m_port, (byte) button);
}
/**
* For the current joystick, return the number of buttons
*/
public int getButtonCount() {
return m_ds.getStickButtonCount(m_port);
}
/**
* Get the state of a POV on the joystick.
*
* @param pov The index of the POV to read (starting at 0)
* @return the angle of the POV in degrees, or -1 if the POV is not pressed.
*/
public int getPOV(int pov) {
return m_ds.getStickPOV(m_port, pov);
}
/**
* For the current joystick, return the number of POVs
*/
public int getPOVCount() {
return m_ds.getStickPOVCount(m_port);
}
/**
* Get buttons based on an enumerated type.
*
* The button type will be looked up in the list of buttons and then read.
*
* @param button The type of button to read.
* @return The state of the button.
*/
public boolean getButton(ButtonType button) {
switch (button.value) {
case ButtonType.kTrigger_val:
return getTrigger();
case ButtonType.kTop_val:
return getTop();
default:
return false;
}
}
/**
* Get the magnitude of the direction vector formed by the joystick's current
* position relative to its origin
*
* @return The magnitude of the direction vector
*/
public double getMagnitude() {
return Math.sqrt(Math.pow(getX(), 2) + Math.pow(getY(), 2));
}
/**
* Get the direction of the vector formed by the joystick and its origin in
* radians
*
* @return The direction of the vector in radians
*/
public double getDirectionRadians() {
return Math.atan2(getX(), -getY());
}
/**
* Get the direction of the vector formed by the joystick and its origin in
* degrees
*
* uses acos(-1) to represent Pi due to absence of readily accessable Pi
* constant in C++
*
* @return The direction of the vector in degrees
*/
public double getDirectionDegrees() {
return Math.toDegrees(getDirectionRadians());
}
/**
* Get the channel currently associated with the specified axis.
*
* @param axis The axis to look up the channel for.
* @return The channel fr the axis.
*/
public int getAxisChannel(AxisType axis) {
return m_axes[axis.value];
}
/**
* Set the channel associated with a specified axis.
*
* @param axis The axis to set the channel for.
* @param channel The channel to set the axis to.
*/
public void setAxisChannel(AxisType axis, int channel) {
m_axes[axis.value] = (byte) channel;
}
/**
* Get the value of isXbox for the current joystick.
*$
* @param value A boolean that is true if the controller is an xbox
* controller.
*/
public boolean getIsXbox() {
return m_ds.getJoystickIsXbox(m_port);
}
/**
* Get the HID type of the current joystick.
*$
* @param value The HID type value of the current joystick.
*/
public int getType() {
return m_ds.getJoystickType(m_port);
}
/**
* Get the name of the current joystick.
*$
* @param value The name of the current joystick.
*/
public String getName() {
return m_ds.getJoystickName(m_port);
}
/**
* Set the rumble output for the joystick. The DS currently supports 2 rumble
* values, left rumble and right rumble
*$
* @param type Which rumble value to set
* @param value The normalized value (0 to 1) to set the rumble to
*/
public void setRumble(RumbleType type, float value) {
if (value < 0)
value = 0;
else if (value > 1)
value = 1;
if (type.value == RumbleType.kLeftRumble_val)
m_leftRumble = (short) (value * 65535);
else
m_rightRumble = (short) (value * 65535);
FRCNetworkCommunicationsLibrary.HALSetJoystickOutputs((byte) m_port, m_outputs, m_leftRumble,
m_rightRumble);
}
/**
* Set a single HID output value for the joystick.
*$
* @param outputNumber The index of the output to set (1-32)
* @param value The value to set the output to
*/
public void setOutput(int outputNumber, boolean value) {
m_outputs = (m_outputs & ~(1 << (outputNumber - 1))) | ((value ? 1 : 0) << (outputNumber - 1));
FRCNetworkCommunicationsLibrary.HALSetJoystickOutputs((byte) m_port, m_outputs, m_leftRumble,
m_rightRumble);
}
/**
* Set all HID output values for the joystick.
*$
* @param value The 32 bit output value (1 bit for each output)
*/
public void setOutputs(int value) {
m_outputs = value;
FRCNetworkCommunicationsLibrary.HALSetJoystickOutputs((byte) m_port, m_outputs, m_leftRumble,
m_rightRumble);
}
}

View File

@@ -0,0 +1,258 @@
package edu.wpi.first.wpilibj;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.lang.Runtime;
import edu.wpi.first.wpilibj.hal.NotifierJNI;
import edu.wpi.first.wpilibj.Utility;
public class Notifier {
static private class ProcessQueue implements Runnable {
public void run() {
Notifier current;
while (true) {
Notifier.queueLock.lock();
double currentTime = Utility.getFPGATime() * 1e-6;
current = Notifier.timerQueueHead;
if (current == null || current.m_expirationTime > currentTime) {
Notifier.queueLock.unlock();
break;
}
Notifier.timerQueueHead = current.m_nextEvent;
if (current.m_periodic) {
current.insertInQueue(true);
} else {
current.m_queued = false;
}
current.m_handlerLock.lock();
Notifier.queueLock.unlock();
current.m_handler.run();
current.m_handlerLock.unlock();
}
Notifier.queueLock.lock();
Notifier.updateAlarm();
Notifier.queueLock.unlock();
}
}
// Maximum time, in seconds, that the FPGA returns before rolling over to 0.
static private final double kRolloverTime = (1l << 32) / 1e6;
// Number of instances of Notifier classes created, so that we can call
// cleanNotifier() after all the Notifiers are stopped.
static private int refcount = 0;
// The next Notifier instance which needs to be called.
static private Notifier timerQueueHead = null;
// The C pointer to the notifier object. We don't use it directly, it is just
// passed to the JNI bindings.
private static long m_notifier;
// The lock for the queue information (namely, timerQueueHead and the
// m_nextEvent members).
private static ReentrantLock queueLock = new ReentrantLock();
// The handler which is called by the HAL library; it handles the subsequent
// calling of the user handlers.
// This is the only Runnable actually passed to the JNI bindings.
private static ProcessQueue m_processQueue;
// The next Notifier whose handler will need to be called after this one.
private Notifier m_nextEvent = null;
// The time, in microseconds, at which the corresponding handler should be
// called. Has the same zero as Utility.getFPGATime().
private double m_expirationTime = 0;
// The handler passed in by the user which should be called at the appropriate
// interval.
private Runnable m_handler;
// Whether we are calling the handler just once or periodically.
private boolean m_periodic = false;
// If periodic, the period of the calling; if just once, stores how long it
// is until we call the handler.
private double m_period = 0;
// Whether we are currently queued to be called at m_expirationTime.
private boolean m_queued = false;
// Lock on the handler so that the handler is not called before it has
// completed. This is only relevant if the handler takes a very long time to
// complete (or the period is very short) and when everything is being
// destructed.
private ReentrantLock m_handlerLock = new ReentrantLock();
/**
* Create a Notifier for timer event notification.
*$
* @param handler The handler is called at the notification time which is set
* using StartSingle or StartPeriodic.
*/
public Notifier(Runnable run) {
if (refcount == 0) {
init();
}
refcount += 1;
m_handler = run;
}
protected void finalize() {
queueLock.lock();
deleteFromQueue();
// If this was the last instance of a Notifier, clean up after ourselves.
if ((--refcount) == 0) {
NotifierJNI.cleanNotifier(m_notifier);
}
queueLock.unlock();
m_handlerLock.lock();
m_handlerLock = null;
}
/**
* Update the alarm hardware to reflect the current first element in the
* queue. Compute the time the next alarm should occur based on the current
* time and the period for the first element in the timer queue. WARNING: this
* method does not do synchronization! It must be called from somewhere that
* is taking care of synchronizing access to the queue.
*/
static protected void updateAlarm() {
if (timerQueueHead != null) {
NotifierJNI.updateNotifierAlarm(m_notifier, (int) (timerQueueHead.m_expirationTime * 1e6));
}
}
/**
* Insert this Notifier into the timer queue in right place. WARNING: this
* method does not do synchronization! It must be called from somewhere that
* is taking care of synchronizing access to the queue.
*$
* @param reschedule If false, the scheduled alarm is based on the current
* time and UpdateAlarm method is called which will enable the alarm if
* necessary. If true, update the time by adding the period (no drift)
* when rescheduled periodic from ProcessQueue. This ensures that the
* public methods only update the queue after finishing inserting.
*/
protected void insertInQueue(boolean reschedule) {
if (reschedule) {
m_expirationTime += m_period;
} else {
m_expirationTime = Utility.getFPGATime() * 1e-6 + m_period;
}
if (m_expirationTime > kRolloverTime) {
m_expirationTime -= kRolloverTime;
}
if (timerQueueHead == null || timerQueueHead.m_expirationTime >= this.m_expirationTime) {
// the queue is empty or greater than the new entry
// the new entry becomes the first element
this.m_nextEvent = timerQueueHead;
timerQueueHead = this;
if (!reschedule) {
// since the first element changed, update alarm, unless we already plan
// to
updateAlarm();
}
} else {
for (Notifier n = timerQueueHead;; n = n.m_nextEvent) {
if (n.m_nextEvent == null || n.m_nextEvent.m_expirationTime > this.m_expirationTime) {
this.m_nextEvent = n.m_nextEvent;
n.m_nextEvent = this;
break;
}
}
}
m_queued = true;
}
/**
* Delete this Notifier from the timer queue. WARNING: this method does not do
* synchronization! It must be called from somewhere that is taking care of
* synchronizing access to the queue. Remove this Notifier from the timer
* queue and adjust the next interrupt time to reflect the current top of the
* queue.
*/
private void deleteFromQueue() {
if (m_queued) {
m_queued = false;
assert (timerQueueHead != null);
if (timerQueueHead == this) {
// removing the first item in the list - update the alarm
timerQueueHead = this.m_nextEvent;
updateAlarm();
} else {
for (Notifier n = timerQueueHead; n != null; n = n.m_nextEvent) {
if (n.m_nextEvent == this) {
// this element is the next element from *n from the queue
// Point n around this.
n.m_nextEvent = this.m_nextEvent;
}
}
}
}
}
/**
* Register for single event notification. A timer event is queued for a
* single event after the specified delay.
*$
* @param delay Seconds to wait before the handler is called.
*/
public void startSingle(double delay) {
queueLock.lock();
m_periodic = false;
m_period = delay;
deleteFromQueue();
insertInQueue(false);
queueLock.unlock();
}
/**
* Register for periodic event notification. A timer event is queued for
* periodic event notification. Each time the interrupt occurs, the event will
* be immediately requeued for the same time interval.
*$
* @param period Period in seconds to call the handler starting one period
* after the call to this method.
*/
public void startPeriodic(double period) {
queueLock.lock();
m_periodic = true;
m_period = period;
deleteFromQueue();
insertInQueue(false);
queueLock.unlock();
}
/**
* Stop timer events from occuring. Stop any repeating timer events from
* occuring. This will also remove any single notification events from the
* queue. If a timer-based call to the registered handler is in progress, this
* function will block until the handler call is complete.
*/
public void stop() {
queueLock.lock();
deleteFromQueue();
queueLock.unlock();
// Wait for a currently executing handler to complete before returning from
// stop()
m_handlerLock.lock();
m_handlerLock.unlock();
}
// First time init.
protected static void init() {
m_processQueue = new ProcessQueue();
m_notifier = NotifierJNI.initializeNotifier(m_processQueue);
}
}

View File

@@ -0,0 +1,463 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType;
import edu.wpi.first.wpilibj.communication.UsageReporting;
import edu.wpi.first.wpilibj.hal.PWMJNI;
import edu.wpi.first.wpilibj.hal.DIOJNI;
import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable;
import edu.wpi.first.wpilibj.tables.ITable;
import edu.wpi.first.wpilibj.tables.ITableListener;
import edu.wpi.first.wpilibj.util.AllocationException;
import edu.wpi.first.wpilibj.util.CheckedAllocationException;
/**
* Class implements the PWM generation in the FPGA.
*
* The values supplied as arguments for PWM outputs range from -1.0 to 1.0. They
* are mapped to the hardware dependent values, in this case 0-2000 for the
* FPGA. Changes are immediately sent to the FPGA, and the update occurs at the
* next FPGA cycle. There is no delay.
*
* As of revision 0.1.10 of the FPGA, the FPGA interprets the 0-2000 values as
* follows: - 2000 = maximum pulse width - 1999 to 1001 = linear scaling from
* "full forward" to "center" - 1000 = center value - 999 to 2 = linear scaling
* from "center" to "full reverse" - 1 = minimum pulse width (currently .5ms) -
* 0 = disabled (i.e. PWM output is held low)
*/
public class PWM extends SensorBase implements LiveWindowSendable {
/**
* Represents the amount to multiply the minimum servo-pulse pwm period by.
*/
public static class PeriodMultiplier {
/**
* The integer value representing this enumeration
*/
public final int value;
static final int k1X_val = 1;
static final int k2X_val = 2;
static final int k4X_val = 4;
/**
* Period Multiplier: don't skip pulses
*/
public static final PeriodMultiplier k1X = new PeriodMultiplier(k1X_val);
/**
* Period Multiplier: skip every other pulse
*/
public static final PeriodMultiplier k2X = new PeriodMultiplier(k2X_val);
/**
* Period Multiplier: skip three out of four pulses
*/
public static final PeriodMultiplier k4X = new PeriodMultiplier(k4X_val);
private PeriodMultiplier(int value) {
this.value = value;
}
}
private int m_channel;
private long m_port;
/**
* kDefaultPwmPeriod is in ms
*
* - 20ms periods (50 Hz) are the "safest" setting in that this works for all
* devices - 20ms periods seem to be desirable for Vex Motors - 20ms periods
* are the specified period for HS-322HD servos, but work reliably down to
* 10.0 ms; starting at about 8.5ms, the servo sometimes hums and get hot; by
* 5.0ms the hum is nearly continuous - 10ms periods work well for Victor 884
* - 5ms periods allows higher update rates for Luminary Micro Jaguar speed
* controllers. Due to the shipping firmware on the Jaguar, we can't run the
* update period less than 5.05 ms.
*
* kDefaultPwmPeriod is the 1x period (5.05 ms). In hardware, the period
* scaling is implemented as an output squelch to get longer periods for old
* devices.
*/
protected static final double kDefaultPwmPeriod = 5.05;
/**
* kDefaultPwmCenter is the PWM range center in ms
*/
protected static final double kDefaultPwmCenter = 1.5;
/**
* kDefaultPWMStepsDown is the number of PWM steps below the centerpoint
*/
protected static final int kDefaultPwmStepsDown = 1000;
public static final int kPwmDisabled = 0;
boolean m_eliminateDeadband;
int m_maxPwm;
int m_deadbandMaxPwm;
int m_centerPwm;
int m_deadbandMinPwm;
int m_minPwm;
/**
* Initialize PWMs given a channel.
*
* This method is private and is the common path for all the constructors for
* creating PWM instances. Checks channel value ranges and allocates the
* appropriate channel. The allocation is only done to help users ensure that
* they don't double assign channels.
*$
* @param channel The PWM channel number. 0-9 are on-board, 10-19 are on the
* MXP port
*/
private void initPWM(final int channel) {
checkPWMChannel(channel);
m_channel = channel;
m_port = DIOJNI.initializeDigitalPort(DIOJNI.getPort((byte) m_channel));
if (!PWMJNI.allocatePWMChannel(m_port)) {
throw new AllocationException("PWM channel " + channel + " is already allocated");
}
PWMJNI.setPWM(m_port, (short) 0);
m_eliminateDeadband = false;
UsageReporting.report(tResourceType.kResourceType_PWM, channel);
}
/**
* Allocate a PWM given a channel.
*
* @param channel The PWM channel.
*/
public PWM(final int channel) {
initPWM(channel);
}
/**
* Free the PWM channel.
*
* Free the resource associated with the PWM channel and set the value to 0.
*/
public void free() {
PWMJNI.setPWM(m_port, (short) 0);
PWMJNI.freePWMChannel(m_port);
PWMJNI.freeDIO(m_port);
}
/**
* Optionally eliminate the deadband from a speed controller.
*$
* @param eliminateDeadband If true, set the motor curve on the Jaguar to
* eliminate the deadband in the middle of the range. Otherwise, keep
* the full range without modifying any values.
*/
public void enableDeadbandElimination(boolean eliminateDeadband) {
m_eliminateDeadband = eliminateDeadband;
}
/**
* Set the bounds on the PWM values. This sets the bounds on the PWM values
* for a particular each type of controller. The values determine the upper
* and lower speeds as well as the deadband bracket.
*$
* @deprecated Recommended to set bounds in ms using
* {@link #setBounds(double, double, double, double, double)}
* @param max The Minimum pwm value
* @param deadbandMax The high end of the deadband range
* @param center The center speed (off)
* @param deadbandMin The low end of the deadband range
* @param min The minimum pwm value
*/
public void setBounds(final int max, final int deadbandMax, final int center,
final int deadbandMin, final int min) {
m_maxPwm = max;
m_deadbandMaxPwm = deadbandMax;
m_centerPwm = center;
m_deadbandMinPwm = deadbandMin;
m_minPwm = min;
}
/**
* Set the bounds on the PWM pulse widths. This sets the bounds on the PWM
* values for a particular type of controller. The values determine the upper
* and lower speeds as well as the deadband bracket.
*$
* @param max The max PWM pulse width in ms
* @param deadbandMax The high end of the deadband range pulse width in ms
* @param center The center (off) pulse width in ms
* @param deadbandMin The low end of the deadband pulse width in ms
* @param min The minimum pulse width in ms
*/
protected void setBounds(double max, double deadbandMax, double center, double deadbandMin,
double min) {
double loopTime =
DIOJNI.getLoopTiming() / (kSystemClockTicksPerMicrosecond * 1e3);
m_maxPwm = (int) ((max - kDefaultPwmCenter) / loopTime + kDefaultPwmStepsDown - 1);
m_deadbandMaxPwm =
(int) ((deadbandMax - kDefaultPwmCenter) / loopTime + kDefaultPwmStepsDown - 1);
m_centerPwm = (int) ((center - kDefaultPwmCenter) / loopTime + kDefaultPwmStepsDown - 1);
m_deadbandMinPwm =
(int) ((deadbandMin - kDefaultPwmCenter) / loopTime + kDefaultPwmStepsDown - 1);
m_minPwm = (int) ((min - kDefaultPwmCenter) / loopTime + kDefaultPwmStepsDown - 1);
}
/**
* Gets the channel number associated with the PWM Object.
*
* @return The channel number.
*/
public int getChannel() {
return m_channel;
}
/**
* Set the PWM value based on a position.
*
* This is intended to be used by servos.
*
* @pre SetMaxPositivePwm() called.
* @pre SetMinNegativePwm() called.
*
* @param pos The position to set the servo between 0.0 and 1.0.
*/
public void setPosition(double pos) {
if (pos < 0.0) {
pos = 0.0;
} else if (pos > 1.0) {
pos = 1.0;
}
int rawValue;
// note, need to perform the multiplication below as floating point before
// converting to int
rawValue = (int) ((pos * (double) getFullRangeScaleFactor()) + getMinNegativePwm());
// send the computed pwm value to the FPGA
setRaw(rawValue);
}
/**
* Get the PWM value in terms of a position.
*
* This is intended to be used by servos.
*
* @pre SetMaxPositivePwm() called.
* @pre SetMinNegativePwm() called.
*
* @return The position the servo is set to between 0.0 and 1.0.
*/
public double getPosition() {
int value = getRaw();
if (value < getMinNegativePwm()) {
return 0.0;
} else if (value > getMaxPositivePwm()) {
return 1.0;
} else {
return (double) (value - getMinNegativePwm()) / (double) getFullRangeScaleFactor();
}
}
/**
* Set the PWM value based on a speed.
*
* This is intended to be used by speed controllers.
*
* @pre SetMaxPositivePwm() called.
* @pre SetMinPositivePwm() called.
* @pre SetCenterPwm() called.
* @pre SetMaxNegativePwm() called.
* @pre SetMinNegativePwm() called.
*
* @param speed The speed to set the speed controller between -1.0 and 1.0.
*/
final void setSpeed(double speed) {
// clamp speed to be in the range 1.0 >= speed >= -1.0
if (speed < -1.0) {
speed = -1.0;
} else if (speed > 1.0) {
speed = 1.0;
}
// calculate the desired output pwm value by scaling the speed appropriately
int rawValue;
if (speed == 0.0) {
rawValue = getCenterPwm();
} else if (speed > 0.0) {
rawValue =
(int) (speed * ((double) getPositiveScaleFactor()) + ((double) getMinPositivePwm()) + 0.5);
} else {
rawValue =
(int) (speed * ((double) getNegativeScaleFactor()) + ((double) getMaxNegativePwm()) + 0.5);
}
// send the computed pwm value to the FPGA
setRaw(rawValue);
}
/**
* Get the PWM value in terms of speed.
*
* This is intended to be used by speed controllers.
*
* @pre SetMaxPositivePwm() called.
* @pre SetMinPositivePwm() called.
* @pre SetMaxNegativePwm() called.
* @pre SetMinNegativePwm() called.
*
* @return The most recently set speed between -1.0 and 1.0.
*/
public double getSpeed() {
int value = getRaw();
if (value > getMaxPositivePwm()) {
return 1.0;
} else if (value < getMinNegativePwm()) {
return -1.0;
} else if (value > getMinPositivePwm()) {
return (double) (value - getMinPositivePwm()) / (double) getPositiveScaleFactor();
} else if (value < getMaxNegativePwm()) {
return (double) (value - getMaxNegativePwm()) / (double) getNegativeScaleFactor();
} else {
return 0.0;
}
}
/**
* Set the PWM value directly to the hardware.
*
* Write a raw value to a PWM channel.
*
* @param value Raw PWM value. Range 0 - 255.
*/
public void setRaw(int value) {
PWMJNI.setPWM(m_port, (short) value);
}
/**
* Get the PWM value directly from the hardware.
*
* Read a raw value from a PWM channel.
*
* @return Raw PWM control value. Range: 0 - 255.
*/
public int getRaw() {
return PWMJNI.getPWM(m_port);
}
/**
* Slow down the PWM signal for old devices.
*
* @param mult The period multiplier to apply to this channel
*/
public void setPeriodMultiplier(PeriodMultiplier mult) {
switch (mult.value) {
case PeriodMultiplier.k4X_val:
// Squelch 3 out of 4 outputs
PWMJNI.setPWMPeriodScale(m_port, 3);
break;
case PeriodMultiplier.k2X_val:
// Squelch 1 out of 2 outputs
PWMJNI.setPWMPeriodScale(m_port, 1);
break;
case PeriodMultiplier.k1X_val:
// Don't squelch any outputs
PWMJNI.setPWMPeriodScale(m_port, 0);
break;
default:
// Cannot hit this, limited by PeriodMultiplier enum
}
}
protected void setZeroLatch() {
PWMJNI.latchPWMZero(m_port);
}
private int getMaxPositivePwm() {
return m_maxPwm;
}
private int getMinPositivePwm() {
return m_eliminateDeadband ? m_deadbandMaxPwm : m_centerPwm + 1;
}
private int getCenterPwm() {
return m_centerPwm;
}
private int getMaxNegativePwm() {
return m_eliminateDeadband ? m_deadbandMinPwm : m_centerPwm - 1;
}
private int getMinNegativePwm() {
return m_minPwm;
}
private int getPositiveScaleFactor() {
return getMaxPositivePwm() - getMinPositivePwm();
} // /< The scale for positive speeds.
private int getNegativeScaleFactor() {
return getMaxNegativePwm() - getMinNegativePwm();
} // /< The scale for negative speeds.
private int getFullRangeScaleFactor() {
return getMaxPositivePwm() - getMinNegativePwm();
} // /< The scale for positions.
/*
* Live Window code, only does anything if live window is activated.
*/
public String getSmartDashboardType() {
return "Speed Controller";
}
private ITable m_table;
private ITableListener m_table_listener;
/**
* {@inheritDoc}
*/
public void initTable(ITable subtable) {
m_table = subtable;
updateTable();
}
/**
* {@inheritDoc}
*/
public void updateTable() {
if (m_table != null) {
m_table.putNumber("Value", getSpeed());
}
}
/**
* {@inheritDoc}
*/
public ITable getTable() {
return m_table;
}
/**
* {@inheritDoc}
*/
public void startLiveWindowMode() {
setSpeed(0); // Stop for safety
m_table_listener = new ITableListener() {
public void valueChanged(ITable itable, String key, Object value, boolean bln) {
setSpeed(((Double) value).doubleValue());
}
};
m_table.addTableListener("Value", m_table_listener, true);
}
/**
* {@inheritDoc}
*/
public void stopLiveWindowMode() {
setSpeed(0); // Stop for safety
// TODO: Broken, should only remove the listener from "Value" only.
m_table.removeTableListener(m_table_listener);
}
}

View File

@@ -0,0 +1,171 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2014. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import edu.wpi.first.wpilibj.hal.PDPJNI;
import edu.wpi.first.wpilibj.hal.HALUtil;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable;
import edu.wpi.first.wpilibj.tables.ITable;
/**
* Class for getting voltage, current, temperature, power and energy from the
* CAN PDP.
*$
* @author Thomas Clark
*/
public class PowerDistributionPanel extends SensorBase implements LiveWindowSendable {
int m_module;
public PowerDistributionPanel(int module) {
m_module = module;
checkPDPModule(m_module);
PDPJNI.initializePDP(m_module);
}
public PowerDistributionPanel() {
this(0);
}
/**
* Query the input voltage of the PDP
*$
* @return The voltage of the PDP in volts
*/
public double getVoltage() {
return PDPJNI.getPDPVoltage(m_module);
}
/**
* Query the temperature of the PDP
*$
* @return The temperature of the PDP in degrees Celsius
*/
public double getTemperature() {
return PDPJNI.getPDPTemperature(m_module);
}
/**
* Query the current of a single channel of the PDP
*$
* @return The current of one of the PDP channels (channels 0-15) in Amperes
*/
public double getCurrent(int channel) {
double current = PDPJNI.getPDPChannelCurrent((byte) channel, m_module);
checkPDPChannel(channel);
return current;
}
/**
* Query the current of all monitored PDP channels (0-15)
*$
* @return The current of all the channels in Amperes
*/
public double getTotalCurrent() {
return PDPJNI.getPDPTotalCurrent(m_module);
}
/**
* Query the total power drawn from the monitored PDP channels
*$
* @return the total power in Watts
*/
public double getTotalPower() {
return PDPJNI.getPDPTotalPower(m_module);
}
/**
* Query the total energy drawn from the monitored PDP channels
*$
* @return the total energy in Joules
*/
public double getTotalEnergy() {
return PDPJNI.getPDPTotalEnergy(m_module);
}
/**
* Reset the total energy to 0
*/
public void resetTotalEnergy() {
PDPJNI.resetPDPTotalEnergy(m_module);
}
/**
* Clear all PDP sticky faults
*/
public void clearStickyFaults() {
PDPJNI.clearPDPStickyFaults(m_module);
}
public String getSmartDashboardType() {
return "PowerDistributionPanel";
}
/*
* Live Window code, only does anything if live window is activated.
*/
private ITable m_table;
/**
* {@inheritDoc}
*/
public void initTable(ITable subtable) {
m_table = subtable;
updateTable();
}
/**
* {@inheritDoc}
*/
public ITable getTable() {
return m_table;
}
/**
* {@inheritDoc}
*/
public void updateTable() {
if (m_table != null) {
m_table.putNumber("Chan0", getCurrent(0));
m_table.putNumber("Chan1", getCurrent(1));
m_table.putNumber("Chan2", getCurrent(2));
m_table.putNumber("Chan3", getCurrent(3));
m_table.putNumber("Chan4", getCurrent(4));
m_table.putNumber("Chan5", getCurrent(5));
m_table.putNumber("Chan6", getCurrent(6));
m_table.putNumber("Chan7", getCurrent(7));
m_table.putNumber("Chan8", getCurrent(8));
m_table.putNumber("Chan9", getCurrent(9));
m_table.putNumber("Chan10", getCurrent(10));
m_table.putNumber("Chan11", getCurrent(11));
m_table.putNumber("Chan12", getCurrent(12));
m_table.putNumber("Chan13", getCurrent(13));
m_table.putNumber("Chan14", getCurrent(14));
m_table.putNumber("Chan15", getCurrent(15));
m_table.putNumber("Voltage", getVoltage());
m_table.putNumber("TotalCurrent", getTotalCurrent());
}
}
/**
* PDP doesn't have to do anything special when entering the LiveWindow.
* {@inheritDoc}
*/
public void startLiveWindowMode() {}
/**
* PDP doesn't have to do anything special when exiting the LiveWindow.
* {@inheritDoc}
*/
public void stopLiveWindowMode() {}
}

View File

@@ -0,0 +1,281 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import java.util.Vector;
import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType;
import edu.wpi.first.wpilibj.communication.UsageReporting;
import edu.wpi.first.wpilibj.networktables.NetworkTable;
import edu.wpi.first.wpilibj.tables.ITable;
import edu.wpi.first.wpilibj.tables.ITableListener;
import edu.wpi.first.wpilibj.tables.TableKeyNotDefinedException;
/**
* The preferences class provides a relatively simple way to save important
* values to the RoboRIO to access the next time the RoboRIO is booted.
*
* <p>
* This class loads and saves from a file inside the RoboRIO. The user can not
* access the file directly, but may modify values at specific fields which will
* then be automatically saved to the file by the NetworkTables server.
* </p>
*
* <p>
* This class is thread safe.
* </p>
*
* <p>
* This will also interact with {@link NetworkTable} by creating a table called
* "Preferences" with all the key-value pairs.
* </p>
*
* @author Joe Grinstead
*/
public class Preferences {
/**
* The Preferences table name
*/
private static final String TABLE_NAME = "Preferences";
/**
* The singleton instance
*/
private static Preferences instance;
/**
* The network table
*/
private NetworkTable table;
/**
* Listener to set all Preferences values to persistent (for backwards
* compatibility with old dashboards).
*/
private final ITableListener listener = new ITableListener() {
@Override
public void valueChanged(ITable table, String key, Object value, boolean isNew) {
// unused
}
@Override
public void valueChangedEx(ITable table, String key, Object value, int flags) {
table.setPersistent(key);
}
};
/**
* Returns the preferences instance.
*
* @return the preferences instance
*/
public synchronized static Preferences getInstance() {
if (instance == null) {
instance = new Preferences();
}
return instance;
}
/**
* Creates a preference class.
*/
private Preferences() {
table = NetworkTable.getTable(TABLE_NAME);
table.addTableListenerEx(listener, ITable.NOTIFY_NEW | ITable.NOTIFY_IMMEDIATE);
UsageReporting.report(tResourceType.kResourceType_Preferences, 0);
}
/**
* @return a vector of the keys
*/
public Vector getKeys() {
Vector<String> keys = new Vector<String>();
for (String key : table.getKeys()) {
keys.add(key);
}
return keys;
}
/**
* Puts the given string into the preferences table.
*
* @param key the key
* @param value the value
* @throws NullPointerException if value is null
*/
public void putString(String key, String value) {
if (value == null) {
throw new NullPointerException();
}
table.putString(key, value);
table.setPersistent(key);
}
/**
* Puts the given int into the preferences table.
*
* @param key the key
* @param value the value
*/
public void putInt(String key, int value) {
table.putNumber(key, value);
table.setPersistent(key);
}
/**
* Puts the given double into the preferences table.
*
* @param key the key
* @param value the value
*/
public void putDouble(String key, double value) {
table.putNumber(key, value);
table.setPersistent(key);
}
/**
* Puts the given float into the preferences table.
*
* @param key the key
* @param value the value
*/
public void putFloat(String key, float value) {
table.putNumber(key, value);
table.setPersistent(key);
}
/**
* Puts the given boolean into the preferences table.
*
* @param key the key
* @param value the value
*/
public void putBoolean(String key, boolean value) {
table.putBoolean(key, value);
table.setPersistent(key);
}
/**
* Puts the given long into the preferences table.
*
* @param key the key
* @param value the value
*/
public void putLong(String key, long value) {
table.putNumber(key, value);
table.setPersistent(key);
}
/**
* Returns whether or not there is a key with the given name.
*
* @param key the key
* @return if there is a value at the given key
*/
public boolean containsKey(String key) {
return table.containsKey(key);
}
/**
* Remove a preference
*
* @param key the key
*/
public void remove(String key) {
table.delete(key);
}
/**
* Returns the string at the given key. If this table does not have a value
* for that position, then the given backup value will be returned.
*
* @param key the key
* @param backup the value to return if none exists in the table
* @return either the value in the table, or the backup
*/
public String getString(String key, String backup) {
return table.getString(key, backup);
}
/**
* Returns the int at the given key. If this table does not have a value for
* that position, then the given backup value will be returned.
*
* @param key the key
* @param backup the value to return if none exists in the table
* @return either the value in the table, or the backup
*/
public int getInt(String key, int backup) {
try {
return (int)table.getNumber(key);
} catch (TableKeyNotDefinedException e) {
return backup;
}
}
/**
* Returns the double at the given key. If this table does not have a value
* for that position, then the given backup value will be returned.
*
* @param key the key
* @param backup the value to return if none exists in the table
* @return either the value in the table, or the backup
*/
public double getDouble(String key, double backup) {
return table.getDouble(key, backup);
}
/**
* Returns the boolean at the given key. If this table does not have a value
* for that position, then the given backup value will be returned.
*
* @param key the key
* @param backup the value to return if none exists in the table
* @return either the value in the table, or the backup
*/
public boolean getBoolean(String key, boolean backup) {
return table.getBoolean(key, backup);
}
/**
* Returns the float at the given key. If this table does not have a value for
* that position, then the given backup value will be returned.
*
* @param key the key
* @param backup the value to return if none exists in the table
* @return either the value in the table, or the backup
*/
public float getFloat(String key, float backup) {
try {
return (float)table.getNumber(key);
} catch (TableKeyNotDefinedException e) {
return backup;
}
}
/**
* Returns the long at the given key. If this table does not have a value for
* that position, then the given backup value will be returned.
*
* @param key the key
* @param backup the value to return if none exists in the table
* @return either the value in the table, or the backup
*/
public long getLong(String key, long backup) {
try {
return (long)table.getNumber(key);
} catch (TableKeyNotDefinedException e) {
return backup;
}
}
/**
* This function is no longer required, as NetworkTables automatically
* saves persistent values (which all Preferences values are) periodically
* when running as a server.
* @deprecated backwards compatibility shim
*/
public void save() {
}
}

View File

@@ -0,0 +1,420 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType;
import edu.wpi.first.wpilibj.communication.UsageReporting;
import edu.wpi.first.wpilibj.hal.DIOJNI;
import edu.wpi.first.wpilibj.hal.RelayJNI;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable;
import edu.wpi.first.wpilibj.tables.ITable;
import edu.wpi.first.wpilibj.tables.ITableListener;
import edu.wpi.first.wpilibj.util.AllocationException;
import edu.wpi.first.wpilibj.util.CheckedAllocationException;
/**
* Class for VEX Robotics Spike style relay outputs. Relays are intended to be
* connected to Spikes or similar relays. The relay channels controls a pair of
* pins that are either both off, one on, the other on, or both on. This
* translates into two Spike outputs at 0v, one at 12v and one at 0v, one at 0v
* and the other at 12v, or two Spike outputs at 12V. This allows off, full
* forward, or full reverse control of motors without variable speed. It also
* allows the two channels (forward and reverse) to be used independently for
* something that does not care about voltage polarity (like a solenoid).
*/
public class Relay extends SensorBase implements MotorSafety, LiveWindowSendable {
private MotorSafetyHelper m_safetyHelper;
/**
* This class represents errors in trying to set relay values contradictory to
* the direction to which the relay is set.
*/
public class InvalidValueException extends RuntimeException {
/**
* Create a new exception with the given message
*
* @param message the message to pass with the exception
*/
public InvalidValueException(String message) {
super(message);
}
}
/**
* The state to drive a Relay to.
*/
public static enum Value {
/**
* value: off
*/
kOff(0),
/**
* value: on for relays with defined direction
*/
kOn(1),
/**
* value: forward
*/
kForward(2),
/**
* value: reverse
*/
kReverse(3);
/**
* The integer value representing this enumeration
*/
public final int value;
private Value(int value) {
this.value = value;
}
}
/**
* The Direction(s) that a relay is configured to operate in.
*/
public static enum Direction {
/**
* direction: both directions are valid
*/
kBoth(0),
/**
* direction: Only forward is valid
*/
kForward(1),
/**
* direction: only reverse is valid
*/
kReverse(2);
/**
* The integer value representing this enumeration
*/
public final int value;
private Direction(int value) {
this.value = value;
}
}
private final int m_channel;
private long m_port;
private Direction m_direction;
private static Resource relayChannels = new Resource(kRelayChannels * 2);
/**
* Common relay initialization method. This code is common to all Relay
* constructors and initializes the relay and reserves all resources that need
* to be locked. Initially the relay is set to both lines at 0v.
*/
private void initRelay() {
SensorBase.checkRelayChannel(m_channel);
try {
if (m_direction == Direction.kBoth || m_direction == Direction.kForward) {
relayChannels.allocate(m_channel * 2);
UsageReporting.report(tResourceType.kResourceType_Relay, m_channel);
}
if (m_direction == Direction.kBoth || m_direction == Direction.kReverse) {
relayChannels.allocate(m_channel * 2 + 1);
UsageReporting.report(tResourceType.kResourceType_Relay, m_channel + 128);
}
} catch (CheckedAllocationException e) {
throw new AllocationException("Relay channel " + m_channel + " is already allocated");
}
m_port = DIOJNI.initializeDigitalPort(DIOJNI.getPort((byte) m_channel));
m_safetyHelper = new MotorSafetyHelper(this);
m_safetyHelper.setSafetyEnabled(false);
LiveWindow.addActuator("Relay", m_channel, this);
}
/**
* Relay constructor given a channel.
*
* @param channel The channel number for this relay (0 - 3).
* @param direction The direction that the Relay object will control.
*/
public Relay(final int channel, Direction direction) {
if (direction == null)
throw new NullPointerException("Null Direction was given");
m_channel = channel;
m_direction = direction;
initRelay();
set(Value.kOff);
}
/**
* Relay constructor given a channel, allowing both directions.
*
* @param channel The channel number for this relay (0 - 3).
*/
public Relay(final int channel) {
this(channel, Direction.kBoth);
}
@Override
public void free() {
if (m_direction == Direction.kBoth || m_direction == Direction.kForward) {
relayChannels.free(m_channel * 2);
}
if (m_direction == Direction.kBoth || m_direction == Direction.kReverse) {
relayChannels.free(m_channel * 2 + 1);
}
RelayJNI.setRelayForward(m_port, false);
RelayJNI.setRelayReverse(m_port, false);
DIOJNI.freeDIO(m_port);
}
/**
* Set the relay state.
*
* Valid values depend on which directions of the relay are controlled by the
* object.
*
* When set to kBothDirections, the relay can be set to any of the four
* states: 0v-0v, 12v-0v, 0v-12v, 12v-12v
*
* When set to kForwardOnly or kReverseOnly, you can specify the constant for
* the direction or you can simply specify kOff_val and kOn_val. Using only
* kOff_val and kOn_val is recommended.
*
* @param value The state to set the relay.
*/
public void set(Value value) {
switch (value) {
case kOff:
if (m_direction == Direction.kBoth || m_direction == Direction.kForward) {
RelayJNI.setRelayForward(m_port, false);
}
if (m_direction == Direction.kBoth || m_direction == Direction.kReverse) {
RelayJNI.setRelayReverse(m_port, false);
}
break;
case kOn:
if (m_direction == Direction.kBoth || m_direction == Direction.kForward) {
RelayJNI.setRelayForward(m_port, true);
}
if (m_direction == Direction.kBoth || m_direction == Direction.kReverse) {
RelayJNI.setRelayReverse(m_port, true);
}
break;
case kForward:
if (m_direction == Direction.kReverse)
throw new InvalidValueException("A relay configured for reverse cannot be set to forward");
if (m_direction == Direction.kBoth || m_direction == Direction.kForward) {
RelayJNI.setRelayForward(m_port, true);
}
if (m_direction == Direction.kBoth) {
RelayJNI.setRelayReverse(m_port, false);
}
break;
case kReverse:
if (m_direction == Direction.kForward)
throw new InvalidValueException("A relay configured for forward cannot be set to reverse");
if (m_direction == Direction.kBoth) {
RelayJNI.setRelayForward(m_port, false);
}
if (m_direction == Direction.kBoth || m_direction == Direction.kReverse) {
RelayJNI.setRelayReverse(m_port, true);
}
break;
default:
// Cannot hit this, limited by Value enum
}
}
/**
* Get the Relay State
*
* Gets the current state of the relay.
*
* When set to kForwardOnly or kReverseOnly, value is returned as kOn/kOff not
* kForward/kReverse (per the recommendation in Set)
*
* @return The current state of the relay as a Relay::Value
*/
public Value get() {
if (RelayJNI.getRelayForward(m_port)) {
if (RelayJNI.getRelayReverse(m_port)) {
return Value.kOn;
} else {
if (m_direction == Direction.kForward) {
return Value.kOn;
} else {
return Value.kForward;
}
}
} else {
if (RelayJNI.getRelayReverse(m_port)) {
if (m_direction == Direction.kReverse) {
return Value.kOn;
} else {
return Value.kReverse;
}
} else {
return Value.kOff;
}
}
}
/**
* Get the channel number.
*
* @return The channel number.
*/
public int getChannel() {
return m_channel;
}
@Override
public void setExpiration(double timeout) {
m_safetyHelper.setExpiration(timeout);
}
@Override
public double getExpiration() {
return m_safetyHelper.getExpiration();
}
@Override
public boolean isAlive() {
return m_safetyHelper.isAlive();
}
@Override
public void stopMotor() {
set(Value.kOff);
}
@Override
public boolean isSafetyEnabled() {
return m_safetyHelper.isSafetyEnabled();
}
@Override
public void setSafetyEnabled(boolean enabled) {
m_safetyHelper.setSafetyEnabled(enabled);
}
@Override
public String getDescription() {
return "Relay ID " + getChannel();
}
/**
* Set the Relay Direction
*
* Changes which values the relay can be set to depending on which direction
* is used
*
* Valid inputs are kBothDirections, kForwardOnly, and kReverseOnly
*
* @param direction The direction for the relay to operate in
*/
public void setDirection(Direction direction) {
if (direction == null)
throw new NullPointerException("Null Direction was given");
if (m_direction == direction) {
return;
}
free();
m_direction = direction;
initRelay();
}
/*
* Live Window code, only does anything if live window is activated.
*/
@Override
public String getSmartDashboardType() {
return "Relay";
}
private ITable m_table;
private ITableListener m_table_listener;
/**
* {@inheritDoc}
*/
@Override
public void initTable(ITable subtable) {
m_table = subtable;
updateTable();
}
/**
* {@inheritDoc}
*/
@Override
public ITable getTable() {
return m_table;
}
/**
* {@inheritDoc}
*/
@Override
public void updateTable() {
if (m_table != null) {
if (get() == Value.kOn) {
m_table.putString("Value", "On");
} else if (get() == Value.kForward) {
m_table.putString("Value", "Forward");
} else if (get() == Value.kReverse) {
m_table.putString("Value", "Reverse");
} else {
m_table.putString("Value", "Off");
}
}
}
/**
* {@inheritDoc}
*/
@Override
public void startLiveWindowMode() {
m_table_listener = new ITableListener() {
@Override
public void valueChanged(ITable itable, String key, Object value, boolean bln) {
String val = ((String) value);
if (val.equals("Off")) {
set(Value.kOff);
} else if (val.equals("On")) {
set(Value.kOn);
} else if (val.equals("Forward")) {
set(Value.kForward);
} else if (val.equals("Reverse")) {
set(Value.kReverse);
}
}
};
m_table.addTableListener("Value", m_table_listener, true);
}
/**
* {@inheritDoc}
*/
@Override
public void stopLiveWindowMode() {
// TODO: Broken, should only remove the listener from "Value" only.
m_table.removeTableListener(m_table_listener);
}
}

View File

@@ -0,0 +1,115 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import edu.wpi.first.wpilibj.util.AllocationException;
import edu.wpi.first.wpilibj.util.CheckedAllocationException;
/**
* Track resources in the program. The Resource class is a convenient way of
* keeping track of allocated arbitrary resources in the program. Resources are
* just indicies that have an lower and upper bound that are tracked by this
* class. In the library they are used for tracking allocation of hardware
* channels but this is purely arbitrary. The resource class does not do any
* actual allocation, but simply tracks if a given index is currently in use.
*
* WARNING: this should only be statically allocated. When the program loads
* into memory all the static constructors are called. At that time a linked
* list of all the "Resources" is created. Then when the program actually starts
* - in the Robot constructor, all resources are initialized. This ensures that
* the program is restartable in memory without having to unload/reload.
*/
public class Resource {
private static Resource m_resourceList = null;
private final boolean m_numAllocated[];
private final int m_size;
private final Resource m_nextResource;
/**
* Clears all allocated resources
*/
public static void restartProgram() {
for (Resource r = Resource.m_resourceList; r != null; r = r.m_nextResource) {
for (int i = 0; i < r.m_size; i++) {
r.m_numAllocated[i] = false;
}
}
}
/**
* Allocate storage for a new instance of Resource. Allocate a bool array of
* values that will get initialized to indicate that no resources have been
* allocated yet. The indicies of the resources are 0..size-1.
*
* @param size The number of blocks to allocate
*/
public Resource(final int size) {
m_size = size;
m_numAllocated = new boolean[m_size];
for (int i = 0; i < m_size; i++) {
m_numAllocated[i] = false;
}
m_nextResource = Resource.m_resourceList;
Resource.m_resourceList = this;
}
/**
* Allocate a resource. When a resource is requested, mark it allocated. In
* this case, a free resource value within the range is located and returned
* after it is marked allocated.
*
* @return The index of the allocated block.
* @throws CheckedAllocationException If there are no resources available to
* be allocated.
*/
public int allocate() throws CheckedAllocationException {
for (int i = 0; i < m_size; i++) {
if (m_numAllocated[i] == false) {
m_numAllocated[i] = true;
return i;
}
}
throw new CheckedAllocationException("No available resources");
}
/**
* Allocate a specific resource value. The user requests a specific resource
* value, i.e. channel number and it is verified unallocated, then returned.
*
* @param index The resource to allocate
* @return The index of the allocated block
* @throws CheckedAllocationException If there are no resources available to
* be allocated.
*/
public int allocate(final int index) throws CheckedAllocationException {
if (index >= m_size || index < 0) {
throw new CheckedAllocationException("Index " + index + " out of range");
}
if (m_numAllocated[index] == true) {
throw new CheckedAllocationException("Resource at index " + index + " already allocated");
}
m_numAllocated[index] = true;
return index;
}
/**
* Free an allocated resource. After a resource is no longer needed, for
* example a destructor is called for a channel assignment class, Free will
* release the resource value so it can be reused somewhere else in the
* program.
*
* @param index The index of the resource to free.
*/
public void free(final int index) {
if (m_numAllocated[index] == false)
throw new AllocationException("No resource available to be freed");
m_numAllocated[index] = false;
}
}

View File

@@ -0,0 +1,258 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
import java.util.jar.Manifest;
import java.util.Arrays;
import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary;
import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tInstances;
import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType;
import edu.wpi.first.wpilibj.communication.UsageReporting;
import edu.wpi.first.wpilibj.internal.HardwareHLUsageReporting;
import edu.wpi.first.wpilibj.internal.HardwareTimer;
import edu.wpi.first.wpilibj.networktables.NetworkTable;
import edu.wpi.first.wpilibj.Utility;
/**
* Implement a Robot Program framework. The RobotBase class is intended to be
* subclassed by a user creating a robot program. Overridden autonomous() and
* operatorControl() methods are called at the appropriate time as the match
* proceeds. In the current implementation, the Autonomous code will run to
* completion before the OperatorControl code could start. In the future the
* Autonomous code might be spawned as a task, then killed at the end of the
* Autonomous period.
*/
public abstract class RobotBase {
/**
* The VxWorks priority that robot code should work at (so Java code should
* run at)
*/
public static final int ROBOT_TASK_PRIORITY = 101;
protected final DriverStation m_ds;
/**
* Constructor for a generic robot program. User code should be placed in the
* constructor that runs before the Autonomous or Operator Control period
* starts. The constructor will run to completion before Autonomous is
* entered.
*
* This must be used to ensure that the communications code starts. In the
* future it would be nice to put this code into it's own task that loads on
* boot so ensure that it runs.
*/
protected RobotBase() {
// TODO: StartCAPI();
// TODO: See if the next line is necessary
// Resource.RestartProgram();
NetworkTable.setNetworkIdentity("Robot");
NetworkTable.setServerMode();// must be before b
m_ds = DriverStation.getInstance();
NetworkTable.getTable(""); // forces network tables to initialize
NetworkTable.getTable("LiveWindow").getSubTable("~STATUS~").putBoolean("LW Enabled", false);
}
/**
* Free the resources for a RobotBase class.
*/
public void free() {}
/**
* @return If the robot is running in simulation.
*/
public static boolean isSimulation() {
return false;
}
/**
* @return If the robot is running in the real world.
*/
public static boolean isReal() {
return true;
}
/**
* Determine if the Robot is currently disabled.
*$
* @return True if the Robot is currently disabled by the field controls.
*/
public boolean isDisabled() {
return m_ds.isDisabled();
}
/**
* Determine if the Robot is currently enabled.
*$
* @return True if the Robot is currently enabled by the field controls.
*/
public boolean isEnabled() {
return m_ds.isEnabled();
}
/**
* Determine if the robot is currently in Autonomous mode.
*$
* @return True if the robot is currently operating Autonomously as determined
* by the field controls.
*/
public boolean isAutonomous() {
return m_ds.isAutonomous();
}
/**
* Determine if the robot is currently in Test mode
*$
* @return True if the robot is currently operating in Test mode as determined
* by the driver station.
*/
public boolean isTest() {
return m_ds.isTest();
}
/**
* Determine if the robot is currently in Operator Control mode.
*$
* @return True if the robot is currently operating in Tele-Op mode as
* determined by the field controls.
*/
public boolean isOperatorControl() {
return m_ds.isOperatorControl();
}
/**
* Indicates if new data is available from the driver station.
*$
* @return Has new data arrived over the network since the last time this
* function was called?
*/
public boolean isNewDataAvailable() {
return m_ds.isNewControlData();
}
/**
* Provide an alternate "main loop" via startCompetition().
*/
public abstract void startCompetition();
public static boolean getBooleanProperty(String name, boolean defaultValue) {
String propVal = System.getProperty(name);
if (propVal == null) {
return defaultValue;
}
if (propVal.equalsIgnoreCase("false")) {
return false;
} else if (propVal.equalsIgnoreCase("true")) {
return true;
} else {
throw new IllegalStateException(propVal);
}
}
/**
* Common initialization for all robot programs.
*/
public static void initializeHardwareConfiguration() {
FRCNetworkCommunicationsLibrary.FRCNetworkCommunicationReserve();
// Set some implementations so that the static methods work properly
Timer.SetImplementation(new HardwareTimer());
HLUsageReporting.SetImplementation(new HardwareHLUsageReporting());
RobotState.SetImplementation(DriverStation.getInstance());
}
/**
* Starting point for the applications.
*/
public static void main(String args[]) {
initializeHardwareConfiguration();
UsageReporting.report(tResourceType.kResourceType_Language, tInstances.kLanguage_Java);
String robotName = "";
Enumeration<URL> resources = null;
try {
resources = RobotBase.class.getClassLoader().getResources("META-INF/MANIFEST.MF");
} catch (IOException e) {
e.printStackTrace();
}
while (resources != null && resources.hasMoreElements()) {
try {
Manifest manifest = new Manifest(resources.nextElement().openStream());
robotName = manifest.getMainAttributes().getValue("Robot-Class");
} catch (IOException e) {
e.printStackTrace();
}
}
RobotBase robot;
try {
robot = (RobotBase) Class.forName(robotName).newInstance();
} catch (Throwable t) {
DriverStation.reportError("ERROR Unhandled exception instantiating robot " + robotName + " "
+ t.toString() + " at " + Arrays.toString(t.getStackTrace()), false);
System.err.println("WARNING: Robots don't quit!");
System.err.println("ERROR: Could not instantiate robot " + robotName + "!");
System.exit(1);
return;
}
File file = null;
FileOutputStream output = null;
try {
file = new File("/tmp/frc_versions/FRC_Lib_Version.ini");
if (file.exists())
file.delete();
file.createNewFile();
output = new FileOutputStream(file);
output.write("2016 Java Beta2.0".getBytes());
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException ex) {
}
}
}
boolean errorOnExit = false;
try {
robot.startCompetition();
} catch (Throwable t) {
DriverStation.reportError(
"ERROR Unhandled exception: " + t.toString() + " at "
+ Arrays.toString(t.getStackTrace()), false);
errorOnExit = true;
} finally {
// startCompetition never returns unless exception occurs....
System.err.println("WARNING: Robots don't quit!");
if (errorOnExit) {
System.err
.println("---> The startCompetition() method (or methods called by it) should have handled the exception above.");
} else {
System.err.println("---> Unexpected return from startCompetition() method.");
}
}
System.exit(1);
}
}

View File

@@ -0,0 +1,829 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tInstances;
import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType;
import edu.wpi.first.wpilibj.communication.UsageReporting;
/**
* Utility class for handling Robot drive based on a definition of the motor
* configuration. The robot drive class handles basic driving for a robot.
* Currently, 2 and 4 motor tank and mecanum drive trains are supported. In the
* future other drive types like swerve might be implemented. Motor channel
* numbers are supplied on creation of the class. Those are used for either the
* drive function (intended for hand created drive code, such as autonomous) or
* with the Tank/Arcade functions intended to be used for Operator Control
* driving.
*/
public class RobotDrive implements MotorSafety {
protected MotorSafetyHelper m_safetyHelper;
/**
* The location of a motor on the robot for the purpose of driving
*/
public static class MotorType {
/**
* The integer value representing this enumeration
*/
public final int value;
static final int kFrontLeft_val = 0;
static final int kFrontRight_val = 1;
static final int kRearLeft_val = 2;
static final int kRearRight_val = 3;
/**
* motortype: front left
*/
public static final MotorType kFrontLeft = new MotorType(kFrontLeft_val);
/**
* motortype: front right
*/
public static final MotorType kFrontRight = new MotorType(kFrontRight_val);
/**
* motortype: rear left
*/
public static final MotorType kRearLeft = new MotorType(kRearLeft_val);
/**
* motortype: rear right
*/
public static final MotorType kRearRight = new MotorType(kRearRight_val);
private MotorType(int value) {
this.value = value;
}
}
public static final double kDefaultExpirationTime = 0.1;
public static final double kDefaultSensitivity = 0.5;
public static final double kDefaultMaxOutput = 1.0;
protected static final int kMaxNumberOfMotors = 4;
protected double m_sensitivity;
protected double m_maxOutput;
protected SpeedController m_frontLeftMotor;
protected SpeedController m_frontRightMotor;
protected SpeedController m_rearLeftMotor;
protected SpeedController m_rearRightMotor;
protected boolean m_allocatedSpeedControllers;
protected byte m_syncGroup = 0;
protected static boolean kArcadeRatioCurve_Reported = false;
protected static boolean kTank_Reported = false;
protected static boolean kArcadeStandard_Reported = false;
protected static boolean kMecanumCartesian_Reported = false;
protected static boolean kMecanumPolar_Reported = false;
/**
* Constructor for RobotDrive with 2 motors specified with channel numbers.
* Set up parameters for a two wheel drive system where the left and right
* motor pwm channels are specified in the call. This call assumes Talons for
* controlling the motors.
*$
* @param leftMotorChannel The PWM channel number that drives the left motor.
* @param rightMotorChannel The PWM channel number that drives the right
* motor.
*/
public RobotDrive(final int leftMotorChannel, final int rightMotorChannel) {
m_sensitivity = kDefaultSensitivity;
m_maxOutput = kDefaultMaxOutput;
m_frontLeftMotor = null;
m_rearLeftMotor = new Talon(leftMotorChannel);
m_frontRightMotor = null;
m_rearRightMotor = new Talon(rightMotorChannel);
m_allocatedSpeedControllers = true;
setupMotorSafety();
drive(0, 0);
}
/**
* Constructor for RobotDrive with 4 motors specified with channel numbers.
* Set up parameters for a four wheel drive system where all four motor pwm
* channels are specified in the call. This call assumes Talons for
* controlling the motors.
*$
* @param frontLeftMotor Front left motor channel number
* @param rearLeftMotor Rear Left motor channel number
* @param frontRightMotor Front right motor channel number
* @param rearRightMotor Rear Right motor channel number
*/
public RobotDrive(final int frontLeftMotor, final int rearLeftMotor, final int frontRightMotor,
final int rearRightMotor) {
m_sensitivity = kDefaultSensitivity;
m_maxOutput = kDefaultMaxOutput;
m_rearLeftMotor = new Talon(rearLeftMotor);
m_rearRightMotor = new Talon(rearRightMotor);
m_frontLeftMotor = new Talon(frontLeftMotor);
m_frontRightMotor = new Talon(frontRightMotor);
m_allocatedSpeedControllers = true;
setupMotorSafety();
drive(0, 0);
}
/**
* Constructor for RobotDrive with 2 motors specified as SpeedController
* objects. The SpeedController version of the constructor enables programs to
* use the RobotDrive classes with subclasses of the SpeedController objects,
* for example, versions with ramping or reshaping of the curve to suit motor
* bias or dead-band elimination.
*$
* @param leftMotor The left SpeedController object used to drive the robot.
* @param rightMotor the right SpeedController object used to drive the robot.
*/
public RobotDrive(SpeedController leftMotor, SpeedController rightMotor) {
if (leftMotor == null || rightMotor == null) {
m_rearLeftMotor = m_rearRightMotor = null;
throw new NullPointerException("Null motor provided");
}
m_frontLeftMotor = null;
m_rearLeftMotor = leftMotor;
m_frontRightMotor = null;
m_rearRightMotor = rightMotor;
m_sensitivity = kDefaultSensitivity;
m_maxOutput = kDefaultMaxOutput;
m_allocatedSpeedControllers = false;
setupMotorSafety();
drive(0, 0);
}
/**
* Constructor for RobotDrive with 4 motors specified as SpeedController
* objects. Speed controller input version of RobotDrive (see previous
* comments).
*$
* @param rearLeftMotor The back left SpeedController object used to drive the
* robot.
* @param frontLeftMotor The front left SpeedController object used to drive
* the robot
* @param rearRightMotor The back right SpeedController object used to drive
* the robot.
* @param frontRightMotor The front right SpeedController object used to drive
* the robot.
*/
public RobotDrive(SpeedController frontLeftMotor, SpeedController rearLeftMotor,
SpeedController frontRightMotor, SpeedController rearRightMotor) {
if (frontLeftMotor == null || rearLeftMotor == null || frontRightMotor == null
|| rearRightMotor == null) {
m_frontLeftMotor = m_rearLeftMotor = m_frontRightMotor = m_rearRightMotor = null;
throw new NullPointerException("Null motor provided");
}
m_frontLeftMotor = frontLeftMotor;
m_rearLeftMotor = rearLeftMotor;
m_frontRightMotor = frontRightMotor;
m_rearRightMotor = rearRightMotor;
m_sensitivity = kDefaultSensitivity;
m_maxOutput = kDefaultMaxOutput;
m_allocatedSpeedControllers = false;
setupMotorSafety();
drive(0, 0);
}
/**
* Drive the motors at "outputMagnitude" and "curve".
* Both outputMagnitude and curve are -1.0 to +1.0 values, where 0.0
* represents stopped and not turning. curve < 0 will turn left and curve > 0
* will turn right.
*
* The algorithm for steering provides a constant turn radius for any normal
* speed range, both forward and backward. Increasing m_sensitivity causes
* sharper turns for fixed values of curve.
*
* This function will most likely be used in an autonomous routine.
*
* @param outputMagnitude The speed setting for the outside wheel in a turn,
* forward or backwards, +1 to -1.
* @param curve The rate of turn, constant for different forward speeds. Set
* curve < 0 for left turn or curve > 0 for right turn.
* Set curve = e^(-r/w) to get a turn radius r for wheelbase w of your robot.
* Conversely, turn radius r = -ln(curve)*w for a given value of curve and
* wheelbase w.
*/
public void drive(double outputMagnitude, double curve) {
double leftOutput, rightOutput;
if (!kArcadeRatioCurve_Reported) {
UsageReporting.report(tResourceType.kResourceType_RobotDrive, getNumMotors(),
tInstances.kRobotDrive_ArcadeRatioCurve);
kArcadeRatioCurve_Reported = true;
}
if (curve < 0) {
double value = Math.log(-curve);
double ratio = (value - m_sensitivity) / (value + m_sensitivity);
if (ratio == 0) {
ratio = .0000000001;
}
leftOutput = outputMagnitude / ratio;
rightOutput = outputMagnitude;
} else if (curve > 0) {
double value = Math.log(curve);
double ratio = (value - m_sensitivity) / (value + m_sensitivity);
if (ratio == 0) {
ratio = .0000000001;
}
leftOutput = outputMagnitude;
rightOutput = outputMagnitude / ratio;
} else {
leftOutput = outputMagnitude;
rightOutput = outputMagnitude;
}
setLeftRightMotorOutputs(leftOutput, rightOutput);
}
/**
* Provide tank steering using the stored robot configuration. drive the robot
* using two joystick inputs. The Y-axis will be selected from each Joystick
* object.
*$
* @param leftStick The joystick to control the left side of the robot.
* @param rightStick The joystick to control the right side of the robot.
*/
public void tankDrive(GenericHID leftStick, GenericHID rightStick) {
if (leftStick == null || rightStick == null) {
throw new NullPointerException("Null HID provided");
}
tankDrive(leftStick.getY(), rightStick.getY(), true);
}
/**
* Provide tank steering using the stored robot configuration. drive the robot
* using two joystick inputs. The Y-axis will be selected from each Joystick
* object.
*$
* @param leftStick The joystick to control the left side of the robot.
* @param rightStick The joystick to control the right side of the robot.
* @param squaredInputs Setting this parameter to true decreases the
* sensitivity at lower speeds
*/
public void tankDrive(GenericHID leftStick, GenericHID rightStick, boolean squaredInputs) {
if (leftStick == null || rightStick == null) {
throw new NullPointerException("Null HID provided");
}
tankDrive(leftStick.getY(), rightStick.getY(), squaredInputs);
}
/**
* Provide tank steering using the stored robot configuration. This function
* lets you pick the axis to be used on each Joystick object for the left and
* right sides of the robot.
*$
* @param leftStick The Joystick object to use for the left side of the robot.
* @param leftAxis The axis to select on the left side Joystick object.
* @param rightStick The Joystick object to use for the right side of the
* robot.
* @param rightAxis The axis to select on the right side Joystick object.
*/
public void tankDrive(GenericHID leftStick, final int leftAxis, GenericHID rightStick,
final int rightAxis) {
if (leftStick == null || rightStick == null) {
throw new NullPointerException("Null HID provided");
}
tankDrive(leftStick.getRawAxis(leftAxis), rightStick.getRawAxis(rightAxis), true);
}
/**
* Provide tank steering using the stored robot configuration. This function
* lets you pick the axis to be used on each Joystick object for the left and
* right sides of the robot.
*$
* @param leftStick The Joystick object to use for the left side of the robot.
* @param leftAxis The axis to select on the left side Joystick object.
* @param rightStick The Joystick object to use for the right side of the
* robot.
* @param rightAxis The axis to select on the right side Joystick object.
* @param squaredInputs Setting this parameter to true decreases the
* sensitivity at lower speeds
*/
public void tankDrive(GenericHID leftStick, final int leftAxis, GenericHID rightStick,
final int rightAxis, boolean squaredInputs) {
if (leftStick == null || rightStick == null) {
throw new NullPointerException("Null HID provided");
}
tankDrive(leftStick.getRawAxis(leftAxis), rightStick.getRawAxis(rightAxis), squaredInputs);
}
/**
* Provide tank steering using the stored robot configuration. This function
* lets you directly provide joystick values from any source.
*$
* @param leftValue The value of the left stick.
* @param rightValue The value of the right stick.
* @param squaredInputs Setting this parameter to true decreases the
* sensitivity at lower speeds
*/
public void tankDrive(double leftValue, double rightValue, boolean squaredInputs) {
if (!kTank_Reported) {
UsageReporting.report(tResourceType.kResourceType_RobotDrive, getNumMotors(),
tInstances.kRobotDrive_Tank);
kTank_Reported = true;
}
// square the inputs (while preserving the sign) to increase fine control
// while permitting full power
leftValue = limit(leftValue);
rightValue = limit(rightValue);
if (squaredInputs) {
if (leftValue >= 0.0) {
leftValue = (leftValue * leftValue);
} else {
leftValue = -(leftValue * leftValue);
}
if (rightValue >= 0.0) {
rightValue = (rightValue * rightValue);
} else {
rightValue = -(rightValue * rightValue);
}
}
setLeftRightMotorOutputs(leftValue, rightValue);
}
/**
* Provide tank steering using the stored robot configuration. This function
* lets you directly provide joystick values from any source.
*$
* @param leftValue The value of the left stick.
* @param rightValue The value of the right stick.
*/
public void tankDrive(double leftValue, double rightValue) {
tankDrive(leftValue, rightValue, true);
}
/**
* Arcade drive implements single stick driving. Given a single Joystick, the
* class assumes the Y axis for the move value and the X axis for the rotate
* value. (Should add more information here regarding the way that arcade
* drive works.)
*$
* @param stick The joystick to use for Arcade single-stick driving. The
* Y-axis will be selected for forwards/backwards and the X-axis will
* be selected for rotation rate.
* @param squaredInputs If true, the sensitivity will be decreased for small
* values
*/
public void arcadeDrive(GenericHID stick, boolean squaredInputs) {
// simply call the full-featured arcadeDrive with the appropriate values
arcadeDrive(stick.getY(), stick.getX(), squaredInputs);
}
/**
* Arcade drive implements single stick driving. Given a single Joystick, the
* class assumes the Y axis for the move value and the X axis for the rotate
* value. (Should add more information here regarding the way that arcade
* drive works.)
*$
* @param stick The joystick to use for Arcade single-stick driving. The
* Y-axis will be selected for forwards/backwards and the X-axis will
* be selected for rotation rate.
*/
public void arcadeDrive(GenericHID stick) {
this.arcadeDrive(stick, true);
}
/**
* Arcade drive implements single stick driving. Given two joystick instances
* and two axis, compute the values to send to either two or four motors.
*$
* @param moveStick The Joystick object that represents the forward/backward
* direction
* @param moveAxis The axis on the moveStick object to use for
* forwards/backwards (typically Y_AXIS)
* @param rotateStick The Joystick object that represents the rotation value
* @param rotateAxis The axis on the rotation object to use for the rotate
* right/left (typically X_AXIS)
* @param squaredInputs Setting this parameter to true decreases the
* sensitivity at lower speeds
*/
public void arcadeDrive(GenericHID moveStick, final int moveAxis, GenericHID rotateStick,
final int rotateAxis, boolean squaredInputs) {
double moveValue = moveStick.getRawAxis(moveAxis);
double rotateValue = rotateStick.getRawAxis(rotateAxis);
arcadeDrive(moveValue, rotateValue, squaredInputs);
}
/**
* Arcade drive implements single stick driving. Given two joystick instances
* and two axis, compute the values to send to either two or four motors.
*$
* @param moveStick The Joystick object that represents the forward/backward
* direction
* @param moveAxis The axis on the moveStick object to use for
* forwards/backwards (typically Y_AXIS)
* @param rotateStick The Joystick object that represents the rotation value
* @param rotateAxis The axis on the rotation object to use for the rotate
* right/left (typically X_AXIS)
*/
public void arcadeDrive(GenericHID moveStick, final int moveAxis, GenericHID rotateStick,
final int rotateAxis) {
this.arcadeDrive(moveStick, moveAxis, rotateStick, rotateAxis, true);
}
/**
* Arcade drive implements single stick driving. This function lets you
* directly provide joystick values from any source.
*$
* @param moveValue The value to use for forwards/backwards
* @param rotateValue The value to use for the rotate right/left
* @param squaredInputs If set, decreases the sensitivity at low speeds
*/
public void arcadeDrive(double moveValue, double rotateValue, boolean squaredInputs) {
// local variables to hold the computed PWM values for the motors
if (!kArcadeStandard_Reported) {
UsageReporting.report(tResourceType.kResourceType_RobotDrive, getNumMotors(),
tInstances.kRobotDrive_ArcadeStandard);
kArcadeStandard_Reported = true;
}
double leftMotorSpeed;
double rightMotorSpeed;
moveValue = limit(moveValue);
rotateValue = limit(rotateValue);
if (squaredInputs) {
// square the inputs (while preserving the sign) to increase fine control
// while permitting full power
if (moveValue >= 0.0) {
moveValue = (moveValue * moveValue);
} else {
moveValue = -(moveValue * moveValue);
}
if (rotateValue >= 0.0) {
rotateValue = (rotateValue * rotateValue);
} else {
rotateValue = -(rotateValue * rotateValue);
}
}
if (moveValue > 0.0) {
if (rotateValue > 0.0) {
leftMotorSpeed = moveValue - rotateValue;
rightMotorSpeed = Math.max(moveValue, rotateValue);
} else {
leftMotorSpeed = Math.max(moveValue, -rotateValue);
rightMotorSpeed = moveValue + rotateValue;
}
} else {
if (rotateValue > 0.0) {
leftMotorSpeed = -Math.max(-moveValue, rotateValue);
rightMotorSpeed = moveValue + rotateValue;
} else {
leftMotorSpeed = moveValue - rotateValue;
rightMotorSpeed = -Math.max(-moveValue, -rotateValue);
}
}
setLeftRightMotorOutputs(leftMotorSpeed, rightMotorSpeed);
}
/**
* Arcade drive implements single stick driving. This function lets you
* directly provide joystick values from any source.
*$
* @param moveValue The value to use for fowards/backwards
* @param rotateValue The value to use for the rotate right/left
*/
public void arcadeDrive(double moveValue, double rotateValue) {
this.arcadeDrive(moveValue, rotateValue, true);
}
/**
* Drive method for Mecanum wheeled robots.
*
* A method for driving with Mecanum wheeled robots. There are 4 wheels on the
* robot, arranged so that the front and back wheels are toed in 45 degrees.
* When looking at the wheels from the top, the roller axles should form an X
* across the robot.
*
* This is designed to be directly driven by joystick axes.
*
* @param x The speed that the robot should drive in the X direction.
* [-1.0..1.0]
* @param y The speed that the robot should drive in the Y direction. This
* input is inverted to match the forward == -1.0 that joysticks
* produce. [-1.0..1.0]
* @param rotation The rate of rotation for the robot that is completely
* independent of the translation. [-1.0..1.0]
* @param gyroAngle The current angle reading from the gyro. Use this to
* implement field-oriented controls.
*/
public void mecanumDrive_Cartesian(double x, double y, double rotation, double gyroAngle) {
if (!kMecanumCartesian_Reported) {
UsageReporting.report(tResourceType.kResourceType_RobotDrive, getNumMotors(),
tInstances.kRobotDrive_MecanumCartesian);
kMecanumCartesian_Reported = true;
}
double xIn = x;
double yIn = y;
// Negate y for the joystick.
yIn = -yIn;
// Compenstate for gyro angle.
double rotated[] = rotateVector(xIn, yIn, gyroAngle);
xIn = rotated[0];
yIn = rotated[1];
double wheelSpeeds[] = new double[kMaxNumberOfMotors];
wheelSpeeds[MotorType.kFrontLeft_val] = xIn + yIn + rotation;
wheelSpeeds[MotorType.kFrontRight_val] = -xIn + yIn - rotation;
wheelSpeeds[MotorType.kRearLeft_val] = -xIn + yIn + rotation;
wheelSpeeds[MotorType.kRearRight_val] = xIn + yIn - rotation;
normalize(wheelSpeeds);
m_frontLeftMotor.set(wheelSpeeds[MotorType.kFrontLeft_val] * m_maxOutput, m_syncGroup);
m_frontRightMotor.set(wheelSpeeds[MotorType.kFrontRight_val] * m_maxOutput, m_syncGroup);
m_rearLeftMotor.set(wheelSpeeds[MotorType.kRearLeft_val] * m_maxOutput, m_syncGroup);
m_rearRightMotor.set(wheelSpeeds[MotorType.kRearRight_val] * m_maxOutput, m_syncGroup);
if (m_syncGroup != 0) {
CANJaguar.updateSyncGroup(m_syncGroup);
}
if (m_safetyHelper != null)
m_safetyHelper.feed();
}
/**
* Drive method for Mecanum wheeled robots.
*
* A method for driving with Mecanum wheeled robots. There are 4 wheels on the
* robot, arranged so that the front and back wheels are toed in 45 degrees.
* When looking at the wheels from the top, the roller axles should form an X
* across the robot.
*
* @param magnitude The speed that the robot should drive in a given
* direction.
* @param direction The direction the robot should drive in degrees. The
* direction and maginitute are independent of the rotation rate.
* @param rotation The rate of rotation for the robot that is completely
* independent of the magnitute or direction. [-1.0..1.0]
*/
public void mecanumDrive_Polar(double magnitude, double direction, double rotation) {
if (!kMecanumPolar_Reported) {
UsageReporting.report(tResourceType.kResourceType_RobotDrive, getNumMotors(),
tInstances.kRobotDrive_MecanumPolar);
kMecanumPolar_Reported = true;
}
double frontLeftSpeed, rearLeftSpeed, frontRightSpeed, rearRightSpeed;
// Normalized for full power along the Cartesian axes.
magnitude = limit(magnitude) * Math.sqrt(2.0);
// The rollers are at 45 degree angles.
double dirInRad = (direction + 45.0) * 3.14159 / 180.0;
double cosD = Math.cos(dirInRad);
double sinD = Math.sin(dirInRad);
double wheelSpeeds[] = new double[kMaxNumberOfMotors];
wheelSpeeds[MotorType.kFrontLeft_val] = (sinD * magnitude + rotation);
wheelSpeeds[MotorType.kFrontRight_val] = (cosD * magnitude - rotation);
wheelSpeeds[MotorType.kRearLeft_val] = (cosD * magnitude + rotation);
wheelSpeeds[MotorType.kRearRight_val] = (sinD * magnitude - rotation);
normalize(wheelSpeeds);
m_frontLeftMotor.set(wheelSpeeds[MotorType.kFrontLeft_val] * m_maxOutput, m_syncGroup);
m_frontRightMotor.set(wheelSpeeds[MotorType.kFrontRight_val] * m_maxOutput, m_syncGroup);
m_rearLeftMotor.set(wheelSpeeds[MotorType.kRearLeft_val] * m_maxOutput, m_syncGroup);
m_rearRightMotor.set(wheelSpeeds[MotorType.kRearRight_val] * m_maxOutput, m_syncGroup);
if (this.m_syncGroup != 0) {
CANJaguar.updateSyncGroup(m_syncGroup);
}
if (m_safetyHelper != null)
m_safetyHelper.feed();
}
/**
* Holonomic Drive method for Mecanum wheeled robots.
*
* This is an alias to mecanumDrive_Polar() for backward compatability
*
* @param magnitude The speed that the robot should drive in a given
* direction. [-1.0..1.0]
* @param direction The direction the robot should drive. The direction and
* maginitute are independent of the rotation rate.
* @param rotation The rate of rotation for the robot that is completely
* independent of the magnitute or direction. [-1.0..1.0]
*/
void holonomicDrive(float magnitude, float direction, float rotation) {
mecanumDrive_Polar(magnitude, direction, rotation);
}
/**
* Set the speed of the right and left motors. This is used once an
* appropriate drive setup function is called such as twoWheelDrive(). The
* motors are set to "leftSpeed" and "rightSpeed" and includes flipping the
* direction of one side for opposing motors.
*$
* @param leftOutput The speed to send to the left side of the robot.
* @param rightOutput The speed to send to the right side of the robot.
*/
public void setLeftRightMotorOutputs(double leftOutput, double rightOutput) {
if (m_rearLeftMotor == null || m_rearRightMotor == null) {
throw new NullPointerException("Null motor provided");
}
if (m_frontLeftMotor != null) {
m_frontLeftMotor.set(limit(leftOutput) * m_maxOutput, m_syncGroup);
}
m_rearLeftMotor.set(limit(leftOutput) * m_maxOutput, m_syncGroup);
if (m_frontRightMotor != null) {
m_frontRightMotor.set(-limit(rightOutput) * m_maxOutput, m_syncGroup);
}
m_rearRightMotor.set(-limit(rightOutput) * m_maxOutput, m_syncGroup);
if (this.m_syncGroup != 0) {
CANJaguar.updateSyncGroup(m_syncGroup);
}
if (m_safetyHelper != null)
m_safetyHelper.feed();
}
/**
* Limit motor values to the -1.0 to +1.0 range.
*/
protected static double limit(double num) {
if (num > 1.0) {
return 1.0;
}
if (num < -1.0) {
return -1.0;
}
return num;
}
/**
* Normalize all wheel speeds if the magnitude of any wheel is greater than
* 1.0.
*/
protected static void normalize(double wheelSpeeds[]) {
double maxMagnitude = Math.abs(wheelSpeeds[0]);
int i;
for (i = 1; i < kMaxNumberOfMotors; i++) {
double temp = Math.abs(wheelSpeeds[i]);
if (maxMagnitude < temp)
maxMagnitude = temp;
}
if (maxMagnitude > 1.0) {
for (i = 0; i < kMaxNumberOfMotors; i++) {
wheelSpeeds[i] = wheelSpeeds[i] / maxMagnitude;
}
}
}
/**
* Rotate a vector in Cartesian space.
*/
protected static double[] rotateVector(double x, double y, double angle) {
double cosA = Math.cos(angle * (3.14159 / 180.0));
double sinA = Math.sin(angle * (3.14159 / 180.0));
double out[] = new double[2];
out[0] = x * cosA - y * sinA;
out[1] = x * sinA + y * cosA;
return out;
}
/**
* Invert a motor direction. This is used when a motor should run in the
* opposite direction as the drive code would normally run it. Motors that are
* direct drive would be inverted, the drive code assumes that the motors are
* geared with one reversal.
*$
* @param motor The motor index to invert.
* @param isInverted True if the motor should be inverted when operated.
*/
public void setInvertedMotor(MotorType motor, boolean isInverted) {
switch (motor.value) {
case MotorType.kFrontLeft_val:
m_frontLeftMotor.setInverted(isInverted);
break;
case MotorType.kFrontRight_val:
m_frontRightMotor.setInverted(isInverted);
break;
case MotorType.kRearLeft_val:
m_rearLeftMotor.setInverted(isInverted);
break;
case MotorType.kRearRight_val:
m_rearRightMotor.setInverted(isInverted);
break;
}
}
/**
* Set the turning sensitivity.
*
* This only impacts the drive() entry-point.
*$
* @param sensitivity Effectively sets the turning sensitivity (or turn radius
* for a given value)
*/
public void setSensitivity(double sensitivity) {
m_sensitivity = sensitivity;
}
/**
* Configure the scaling factor for using RobotDrive with motor controllers in
* a mode other than PercentVbus.
*$
* @param maxOutput Multiplied with the output percentage computed by the
* drive functions.
*/
public void setMaxOutput(double maxOutput) {
m_maxOutput = maxOutput;
}
/**
* Set the number of the sync group for the motor controllers. If the motor
* controllers are {@link CANJaguar}s, then they will all be added to this
* sync group, causing them to update their values at the same time.
*
* @param syncGroup the update group to add the motor controllers to
*/
public void setCANJaguarSyncGroup(byte syncGroup) {
m_syncGroup = syncGroup;
}
/**
* Free the speed controllers if they were allocated locally
*/
public void free() {
if (m_allocatedSpeedControllers) {
if (m_frontLeftMotor != null) {
((PWM) m_frontLeftMotor).free();
}
if (m_frontRightMotor != null) {
((PWM) m_frontRightMotor).free();
}
if (m_rearLeftMotor != null) {
((PWM) m_rearLeftMotor).free();
}
if (m_rearRightMotor != null) {
((PWM) m_rearRightMotor).free();
}
}
}
public void setExpiration(double timeout) {
m_safetyHelper.setExpiration(timeout);
}
public double getExpiration() {
return m_safetyHelper.getExpiration();
}
public boolean isAlive() {
return m_safetyHelper.isAlive();
}
public boolean isSafetyEnabled() {
return m_safetyHelper.isSafetyEnabled();
}
public void setSafetyEnabled(boolean enabled) {
m_safetyHelper.setSafetyEnabled(enabled);
}
public String getDescription() {
return "Robot Drive";
}
public void stopMotor() {
if (m_frontLeftMotor != null) {
m_frontLeftMotor.set(0.0);
}
if (m_frontRightMotor != null) {
m_frontRightMotor.set(0.0);
}
if (m_rearLeftMotor != null) {
m_rearLeftMotor.set(0.0);
}
if (m_rearRightMotor != null) {
m_rearRightMotor.set(0.0);
}
if (m_safetyHelper != null)
m_safetyHelper.feed();
}
private void setupMotorSafety() {
m_safetyHelper = new MotorSafetyHelper(this);
m_safetyHelper.setExpiration(kDefaultExpirationTime);
m_safetyHelper.setSafetyEnabled(true);
}
protected int getNumMotors() {
int motors = 0;
if (m_frontLeftMotor != null)
motors++;
if (m_frontRightMotor != null)
motors++;
if (m_rearLeftMotor != null)
motors++;
if (m_rearRightMotor != null)
motors++;
return motors;
}
}

View File

@@ -0,0 +1,256 @@
package edu.wpi.first.wpilibj;
import java.nio.ByteBuffer;
import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType;
import edu.wpi.first.wpilibj.communication.UsageReporting;
import edu.wpi.first.wpilibj.hal.HALLibrary;
import edu.wpi.first.wpilibj.hal.SPIJNI;
/**
*
* Represents a SPI bus port
*$
* @author koconnor
*/
public class SPI extends SensorBase {
public enum Port {
kOnboardCS0(0), kOnboardCS1(1), kOnboardCS2(2), kOnboardCS3(3), kMXP(4);
private int value;
private Port(int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
};
private static int devices = 0;
private byte m_port;
private int bitOrder;
private int clockPolarity;
private int dataOnTrailing;
/**
* Constructor
*
* @param port the physical SPI port
*/
public SPI(Port port) {
m_port = (byte) port.getValue();
devices++;
SPIJNI.spiInitialize(m_port);
UsageReporting.report(tResourceType.kResourceType_SPI, devices);
}
/**
* Free the resources used by this object
*/
public void free() {
SPIJNI.spiClose(m_port);
}
/**
* Configure the rate of the generated clock signal. The default value is
* 500,000 Hz. The maximum value is 4,000,000 Hz.
*
* @param hz The clock rate in Hertz.
*/
public final void setClockRate(int hz) {
SPIJNI.spiSetSpeed(m_port, hz);
}
/**
* Configure the order that bits are sent and received on the wire to be most
* significant bit first.
*/
public final void setMSBFirst() {
this.bitOrder = 1;
SPIJNI.spiSetOpts(m_port, this.bitOrder, this.dataOnTrailing, this.clockPolarity);
}
/**
* Configure the order that bits are sent and received on the wire to be least
* significant bit first.
*/
public final void setLSBFirst() {
this.bitOrder = 0;
SPIJNI.spiSetOpts(m_port, this.bitOrder, this.dataOnTrailing, this.clockPolarity);
}
/**
* Configure the clock output line to be active low. This is sometimes called
* clock polarity high or clock idle high.
*/
public final void setClockActiveLow() {
this.clockPolarity = 1;
SPIJNI.spiSetOpts(m_port, this.bitOrder, this.dataOnTrailing, this.clockPolarity);
}
/**
* Configure the clock output line to be active high. This is sometimes called
* clock polarity low or clock idle low.
*/
public final void setClockActiveHigh() {
this.clockPolarity = 0;
SPIJNI.spiSetOpts(m_port, this.bitOrder, this.dataOnTrailing, this.clockPolarity);
}
/**
* Configure that the data is stable on the falling edge and the data changes
* on the rising edge.
*/
public final void setSampleDataOnFalling() {
this.dataOnTrailing = 1;
SPIJNI.spiSetOpts(m_port, this.bitOrder, this.dataOnTrailing, this.clockPolarity);
}
/**
* Configure that the data is stable on the rising edge and the data changes
* on the falling edge.
*/
public final void setSampleDataOnRising() {
this.dataOnTrailing = 0;
SPIJNI.spiSetOpts(m_port, this.bitOrder, this.dataOnTrailing, this.clockPolarity);
}
/**
* Configure the chip select line to be active high.
*/
public final void setChipSelectActiveHigh() {
SPIJNI.spiSetChipSelectActiveHigh(m_port);
}
/**
* Configure the chip select line to be active low.
*/
public final void setChipSelectActiveLow() {
SPIJNI.spiSetChipSelectActiveLow(m_port);
}
/**
* Write data to the slave device. Blocks until there is space in the output
* FIFO.
*
* If not running in output only mode, also saves the data received on the
* MISO input during the transfer into the receive FIFO.
*/
public int write(byte[] dataToSend, int size) {
ByteBuffer dataToSendBuffer = ByteBuffer.allocateDirect(size);
dataToSendBuffer.put(dataToSend);
return SPIJNI.spiWrite(m_port, dataToSendBuffer, (byte) size);
}
/**
* Write data to the slave device. Blocks until there is space in the output
* FIFO.
*
* If not running in output only mode, also saves the data received on the
* MISO input during the transfer into the receive FIFO.
*
* @param dataToSend The buffer containing the data to send. Must be created
* using ByteBuffer.allocateDirect().
*/
public int write(ByteBuffer dataToSend, int size) {
if (!dataToSend.isDirect())
throw new IllegalArgumentException("must be a direct buffer");
if (dataToSend.capacity() < size)
throw new IllegalArgumentException("buffer is too small, must be at least " + size);
return SPIJNI.spiWrite(m_port, dataToSend, (byte) size);
}
/**
* Read a word from the receive FIFO.
*
* Waits for the current transfer to complete if the receive FIFO is empty.
*
* If the receive FIFO is empty, there is no active transfer, and initiate is
* false, errors.
*
* @param initiate If true, this function pushes "0" into the transmit buffer
* and initiates a transfer. If false, this function assumes that data
* is already in the receive FIFO from a previous write.
*/
public int read(boolean initiate, byte[] dataReceived, int size) {
int retVal = 0;
ByteBuffer dataReceivedBuffer = ByteBuffer.allocateDirect(size);
ByteBuffer dataToSendBuffer = ByteBuffer.allocateDirect(size);
if (initiate)
retVal = SPIJNI.spiTransaction(m_port, dataToSendBuffer, dataReceivedBuffer, (byte) size);
else
retVal = SPIJNI.spiRead(m_port, dataReceivedBuffer, (byte) size);
dataReceivedBuffer.get(dataReceived);
return retVal;
}
/**
* Read a word from the receive FIFO.
*
* Waits for the current transfer to complete if the receive FIFO is empty.
*
* If the receive FIFO is empty, there is no active transfer, and initiate is
* false, errors.
*
* @param initiate If true, this function pushes "0" into the transmit buffer
* and initiates a transfer. If false, this function assumes that data
* is already in the receive FIFO from a previous write.
*
* @param received The buffer to be filled with the received data. Must be
* created using ByteBuffer.allocateDirect().
*/
public int read(boolean initiate, ByteBuffer dataReceived, int size) {
if (!dataReceived.isDirect())
throw new IllegalArgumentException("must be a direct buffer");
if (dataReceived.capacity() < size)
throw new IllegalArgumentException("buffer is too small, must be at least " + size);
if (initiate) {
ByteBuffer dataToSendBuffer = ByteBuffer.allocateDirect(size);
return SPIJNI.spiTransaction(m_port, dataToSendBuffer, dataReceived, (byte) size);
}
return SPIJNI.spiRead(m_port, dataReceived, (byte) size);
}
/**
* Perform a simultaneous read/write transaction with the device
*
* @param dataToSend The data to be written out to the device
* @param dataReceived Buffer to receive data from the device
* @param size The length of the transaction, in bytes
*/
public int transaction(byte[] dataToSend, byte[] dataReceived, int size) {
ByteBuffer dataToSendBuffer = ByteBuffer.allocateDirect(size);
dataToSendBuffer.put(dataToSend);
ByteBuffer dataReceivedBuffer = ByteBuffer.allocateDirect(size);
int retVal = SPIJNI.spiTransaction(m_port, dataToSendBuffer, dataReceivedBuffer, (byte) size);
dataReceivedBuffer.get(dataReceived);
return retVal;
}
/**
* Perform a simultaneous read/write transaction with the device
*
* @param dataToSend The data to be written out to the device. Must be
* created using ByteBuffer.allocateDirect().
* @param dataReceived Buffer to receive data from the device. Must be
* created using ByteBuffer.allocateDirect().
* @param size The length of the transaction, in bytes
*/
public int transaction(ByteBuffer dataToSend, ByteBuffer dataReceived, int size) {
if (!dataToSend.isDirect())
throw new IllegalArgumentException("dataToSend must be a direct buffer");
if (dataToSend.capacity() < size)
throw new IllegalArgumentException("dataToSend is too small, must be at least " + size);
if (!dataReceived.isDirect())
throw new IllegalArgumentException("dataReceived must be a direct buffer");
if (dataReceived.capacity() < size)
throw new IllegalArgumentException("dataReceived is too small, must be at least " + size);
return SPIJNI.spiTransaction(m_port, dataToSend, dataReceived, (byte) size);
}
}

View File

@@ -0,0 +1,27 @@
/*
* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org). Version
* 2.0.11
*$
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* -----------------------------------------------------------------------------
*/
package edu.wpi.first.wpilibj.hal;
public class SWIGTYPE_p_CTR_Code {
private long swigCPtr;
public SWIGTYPE_p_CTR_Code(long cPtr, boolean futureUse) {
swigCPtr = cPtr;
}
public SWIGTYPE_p_CTR_Code() {
swigCPtr = 0;
}
public static long getCPtr(SWIGTYPE_p_CTR_Code obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
}

View File

@@ -0,0 +1,27 @@
/*
* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org). Version
* 2.0.11
*$
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* -----------------------------------------------------------------------------
*/
package edu.wpi.first.wpilibj.hal;
public class SWIGTYPE_p_UINT8 {
private long swigCPtr;
public SWIGTYPE_p_UINT8(long cPtr, boolean futureUse) {
swigCPtr = cPtr;
}
public SWIGTYPE_p_UINT8() {
swigCPtr = 0;
}
public static long getCPtr(SWIGTYPE_p_UINT8 obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
}

View File

@@ -0,0 +1,27 @@
/*
* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org). Version
* 2.0.11
*$
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* -----------------------------------------------------------------------------
*/
package edu.wpi.first.wpilibj.hal;
public class SWIGTYPE_p_double {
private long swigCPtr;
public SWIGTYPE_p_double(long cPtr, boolean futureUse) {
swigCPtr = cPtr;
}
public SWIGTYPE_p_double() {
swigCPtr = 0;
}
public static long getCPtr(SWIGTYPE_p_double obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
}

View File

@@ -0,0 +1,27 @@
/*
* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org). Version
* 2.0.11
*$
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* -----------------------------------------------------------------------------
*/
package edu.wpi.first.wpilibj.hal;
public class SWIGTYPE_p_float {
private long swigCPtr;
public SWIGTYPE_p_float(long cPtr, boolean futureUse) {
swigCPtr = cPtr;
}
public SWIGTYPE_p_float() {
swigCPtr = 0;
}
public static long getCPtr(SWIGTYPE_p_float obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
}

View File

@@ -0,0 +1,27 @@
/*
* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org). Version
* 2.0.11
*$
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* -----------------------------------------------------------------------------
*/
package edu.wpi.first.wpilibj.hal;
public class SWIGTYPE_p_int {
private long swigCPtr;
public SWIGTYPE_p_int(long cPtr, boolean futureUse) {
swigCPtr = cPtr;
}
public SWIGTYPE_p_int() {
swigCPtr = 0;
}
public static long getCPtr(SWIGTYPE_p_int obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
}

View File

@@ -0,0 +1,27 @@
/*
* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org). Version
* 2.0.11
*$
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* -----------------------------------------------------------------------------
*/
package edu.wpi.first.wpilibj.hal;
public class SWIGTYPE_p_int32_t {
private long swigCPtr;
public SWIGTYPE_p_int32_t(long cPtr, boolean futureUse) {
swigCPtr = cPtr;
}
public SWIGTYPE_p_int32_t() {
swigCPtr = 0;
}
public static long getCPtr(SWIGTYPE_p_int32_t obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
}

View File

@@ -0,0 +1,27 @@
/*
* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org). Version
* 2.0.11
*$
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* -----------------------------------------------------------------------------
*/
package edu.wpi.first.wpilibj.hal;
public class SWIGTYPE_p_uint32_t {
private long swigCPtr;
public SWIGTYPE_p_uint32_t(long cPtr, boolean futureUse) {
swigCPtr = cPtr;
}
public SWIGTYPE_p_uint32_t() {
swigCPtr = 0;
}
public static long getCPtr(SWIGTYPE_p_uint32_t obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
}

View File

@@ -0,0 +1,27 @@
/*
* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org). Version
* 2.0.11
*$
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* -----------------------------------------------------------------------------
*/
package edu.wpi.first.wpilibj.hal;
public class SWIGTYPE_p_uint8_t {
private long swigCPtr;
public SWIGTYPE_p_uint8_t(long cPtr, boolean futureUse) {
swigCPtr = cPtr;
}
public SWIGTYPE_p_uint8_t() {
swigCPtr = 0;
}
public static long getCPtr(SWIGTYPE_p_uint8_t obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
}

View File

@@ -0,0 +1,104 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
/**
*
* @author brad
*/
public class SafePWM extends PWM implements MotorSafety {
private MotorSafetyHelper m_safetyHelper;
/**
* Initialize a SafePWM object by setting defaults
*/
void initSafePWM() {
m_safetyHelper = new MotorSafetyHelper(this);
m_safetyHelper.setExpiration(0.0);
m_safetyHelper.setSafetyEnabled(false);
}
/**
* Constructor for a SafePWM object taking a channel number
*$
* @param channel The channel number to be used for the underlying PWM object.
* 0-9 are on-board, 10-19 are on the MXP port.
*/
public SafePWM(final int channel) {
super(channel);
initSafePWM();
}
/*
* Set the expiration time for the PWM object
*$
* @param timeout The timeout (in seconds) for this motor object
*/
public void setExpiration(double timeout) {
m_safetyHelper.setExpiration(timeout);
}
/**
* Return the expiration time for the PWM object.
*$
* @return The expiration time value.
*/
public double getExpiration() {
return m_safetyHelper.getExpiration();
}
/**
* Check if the PWM object is currently alive or stopped due to a timeout.
*$
* @return a bool value that is true if the motor has NOT timed out and should
* still be running.
*/
public boolean isAlive() {
return m_safetyHelper.isAlive();
}
/**
* Stop the motor associated with this PWM object. This is called by the
* MotorSafetyHelper object when it has a timeout for this PWM and needs to
* stop it from running.
*/
public void stopMotor() {
disable();
}
/**
* Check if motor safety is enabled for this object
*$
* @return True if motor safety is enforced for this object
*/
public boolean isSafetyEnabled() {
return m_safetyHelper.isSafetyEnabled();
}
/**
* Feed the MotorSafety timer. This method is called by the subclass motor
* whenever it updates its speed, thereby reseting the timeout value.
*/
public void Feed() {
m_safetyHelper.feed();
}
public void setSafetyEnabled(boolean enabled) {
m_safetyHelper.setSafetyEnabled(enabled);
}
public String getDescription() {
return "PWM " + getChannel();
}
public void disable() {
setRaw(kPwmDisabled);
}
}

View File

@@ -0,0 +1,168 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import edu.wpi.first.wpilibj.communication.UsageReporting;
import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary;
import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tInstances;
import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
/**
* A simple robot base class that knows the standard FRC competition states
* (disabled, autonomous, or operator controlled).
*
* You can build a simple robot program off of this by overriding the
* robotinit(), disabled(), autonomous() and operatorControl() methods. The
* startCompetition() method will calls these methods (sometimes repeatedly).
* depending on the state of the competition.
*
* Alternatively you can override the robotMain() method and manage all aspects
* of the robot yourself.
*/
public class SampleRobot extends RobotBase {
private boolean m_robotMainOverridden;
/**
* Create a new SampleRobot
*/
public SampleRobot() {
super();
m_robotMainOverridden = true;
}
/**
* Robot-wide initialization code should go here.
*
* Users should override this method for default Robot-wide initialization
* which will be called when the robot is first powered on. It will be called
* exactly one time.
*
* Warning: the Driver Station "Robot Code" light and FMS "Robot Ready"
* indicators will be off until RobotInit() exits. Code in RobotInit() that
* waits for enable will cause the robot to never indicate that the code is
* ready, causing the robot to be bypassed in a match.
*/
protected void robotInit() {
System.out.println("Default robotInit() method running, consider providing your own");
}
/**
* Disabled should go here. Users should overload this method to run code that
* should run while the field is disabled.
*
* Called once each time the robot enters the disabled state.
*/
protected void disabled() {
System.out.println("Default disabled() method running, consider providing your own");
}
/**
* Autonomous should go here. Users should add autonomous code to this method
* that should run while the field is in the autonomous period.
*
* Called once each time the robot enters the autonomous state.
*/
public void autonomous() {
System.out.println("Default autonomous() method running, consider providing your own");
}
/**
* Operator control (tele-operated) code should go here. Users should add
* Operator Control code to this method that should run while the field is in
* the Operator Control (tele-operated) period.
*
* Called once each time the robot enters the operator-controlled state.
*/
public void operatorControl() {
System.out.println("Default operatorControl() method running, consider providing your own");
}
/**
* Test code should go here. Users should add test code to this method that
* should run while the robot is in test mode.
*/
public void test() {
System.out.println("Default test() method running, consider providing your own");
}
/**
* Robot main program for free-form programs.
*
* This should be overridden by user subclasses if the intent is to not use
* the autonomous() and operatorControl() methods. In that case, the program
* is responsible for sensing when to run the autonomous and operator control
* functions in their program.
*
* This method will be called immediately after the constructor is called. If
* it has not been overridden by a user subclass (i.e. the default version
* runs), then the robotInit(), disabled(), autonomous() and operatorControl()
* methods will be called.
*/
public void robotMain() {
m_robotMainOverridden = false;
}
/**
* Start a competition. This code tracks the order of the field starting to
* ensure that everything happens in the right order. Repeatedly run the
* correct method, either Autonomous or OperatorControl when the robot is
* enabled. After running the correct method, wait for some state to change,
* either the other mode starts or the robot is disabled. Then go back and
* wait for the robot to be enabled again.
*/
public void startCompetition() {
UsageReporting.report(tResourceType.kResourceType_Framework, tInstances.kFramework_Sample);
robotInit();
// Tell the DS that the robot is ready to be enabled
FRCNetworkCommunicationsLibrary.FRCNetworkCommunicationObserveUserProgramStarting();
robotMain();
if (!m_robotMainOverridden) {
// first and one-time initialization
LiveWindow.setEnabled(false);
while (true) {
if (isDisabled()) {
m_ds.InDisabled(true);
disabled();
m_ds.InDisabled(false);
while (isDisabled()) {
Timer.delay(0.01);
}
} else if (isAutonomous()) {
m_ds.InAutonomous(true);
autonomous();
m_ds.InAutonomous(false);
while (isAutonomous() && !isDisabled()) {
Timer.delay(0.01);
}
} else if (isTest()) {
LiveWindow.setEnabled(true);
m_ds.InTest(true);
test();
m_ds.InTest(false);
while (isTest() && isEnabled())
Timer.delay(0.01);
LiveWindow.setEnabled(false);
} else {
m_ds.InOperatorControl(true);
operatorControl();
m_ds.InOperatorControl(false);
while (isOperatorControl() && !isDisabled()) {
Timer.delay(0.01);
}
}
} /* while loop */
}
}
}

View File

@@ -0,0 +1,200 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import edu.wpi.first.wpilibj.hal.DIOJNI;
import edu.wpi.first.wpilibj.hal.AnalogJNI;
/**
* Base class for all sensors. Stores most recent status information as well as
* containing utility functions for checking channels and error processing.
*/
public abstract class SensorBase { // TODO: Refactor
// TODO: Move this to the HAL
/**
* Ticks per microsecond
*/
public static final int kSystemClockTicksPerMicrosecond = 40;
/**
* Number of digital channels per roboRIO
*/
public static final int kDigitalChannels = 26;
/**
* Number of analog input channels
*/
public static final int kAnalogInputChannels = 8;
/**
* Number of analog output channels
*/
public static final int kAnalogOutputChannels = 2;
/**
* Number of solenoid channels per module
*/
public static final int kSolenoidChannels = 8;
/**
* Number of solenoid modules
*/
public static final int kSolenoidModules = 2;
/**
* Number of PWM channels per roboRIO
*/
public static final int kPwmChannels = 20;
/**
* Number of relay channels per roboRIO
*/
public static final int kRelayChannels = 4;
/**
* Number of power distribution channels
*/
public static final int kPDPChannels = 16;
/**
* Number of power distribution modules
*/
public static final int kPDPModules = 63;
private static int m_defaultSolenoidModule = 0;
/**
* Creates an instance of the sensor base and gets an FPGA handle
*/
public SensorBase() {}
/**
* Set the default location for the Solenoid module.
*
* @param moduleNumber The number of the solenoid module to use.
*/
public static void setDefaultSolenoidModule(final int moduleNumber) {
checkSolenoidModule(moduleNumber);
SensorBase.m_defaultSolenoidModule = moduleNumber;
}
/**
* Verify that the solenoid module is correct.
*
* @param moduleNumber The solenoid module module number to check.
*/
protected static void checkSolenoidModule(final int moduleNumber) {
// if(HALLibrary.checkSolenoidModule((byte) (moduleNumber - 1)) != 0) {
// System.err.println("Solenoid module " + moduleNumber +
// " is not present.");
// }
}
/**
* Check that the digital channel number is valid. Verify that the channel
* number is one of the legal channel numbers. Channel numbers are 1-based.
*
* @param channel The channel number to check.
*/
protected static void checkDigitalChannel(final int channel) {
if (channel < 0 || channel >= kDigitalChannels) {
throw new IndexOutOfBoundsException("Requested digital channel number is out of range.");
}
}
/**
* Check that the digital channel number is valid. Verify that the channel
* number is one of the legal channel numbers. Channel numbers are 1-based.
*
* @param channel The channel number to check.
*/
protected static void checkRelayChannel(final int channel) {
if (channel < 0 || channel >= kRelayChannels) {
throw new IndexOutOfBoundsException("Requested relay channel number is out of range.");
}
}
/**
* Check that the digital channel number is valid. Verify that the channel
* number is one of the legal channel numbers. Channel numbers are 1-based.
*
* @param channel The channel number to check.
*/
protected static void checkPWMChannel(final int channel) {
if (channel < 0 || channel >= kPwmChannels) {
throw new IndexOutOfBoundsException("Requested PWM channel number is out of range.");
}
}
/**
* Check that the analog input number is value. Verify that the analog input
* number is one of the legal channel numbers. Channel numbers are 0-based.
*
* @param channel The channel number to check.
*/
protected static void checkAnalogInputChannel(final int channel) {
if (channel < 0 || channel >= kAnalogInputChannels) {
throw new IndexOutOfBoundsException("Requested analog input channel number is out of range.");
}
}
/**
* Check that the analog input number is value. Verify that the analog input
* number is one of the legal channel numbers. Channel numbers are 0-based.
*
* @param channel The channel number to check.
*/
protected static void checkAnalogOutputChannel(final int channel) {
if (channel < 0 || channel >= kAnalogOutputChannels) {
throw new IndexOutOfBoundsException("Requested analog output channel number is out of range.");
}
}
/**
* Verify that the solenoid channel number is within limits. Channel numbers
* are 1-based.
*
* @param channel The channel number to check.
*/
protected static void checkSolenoidChannel(final int channel) {
if (channel < 0 || channel >= kSolenoidChannels) {
throw new IndexOutOfBoundsException("Requested solenoid channel number is out of range.");
}
}
/**
* Verify that the power distribution channel number is within limits. Channel
* numbers are 1-based.
*
* @param channel The channel number to check.
*/
protected static void checkPDPChannel(final int channel) {
if (channel < 0 || channel >= kPDPChannels) {
throw new IndexOutOfBoundsException("Requested PDP channel number is out of range.");
}
}
/**
* Verify that the PDP module number is within limits. module numbers are
* 0-based.
*$
* @param channel The module number to check.
*/
protected static void checkPDPModule(final int module) {
if (module < 0 || module > kPDPModules) {
throw new IndexOutOfBoundsException("Requested PDP module number is out of range.");
}
}
/**
* Get the number of the default solenoid module.
*
* @return The number of the default solenoid module.
*/
public static int getDefaultSolenoidModule() {
return SensorBase.m_defaultSolenoidModule;
}
/**
* Free the resources used by this object
*/
public void free() {}
}

View File

@@ -0,0 +1,443 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType;
import edu.wpi.first.wpilibj.communication.UsageReporting;
import edu.wpi.first.wpilibj.hal.HALLibrary;
import edu.wpi.first.wpilibj.hal.SerialPortJNI;
/**
* Driver for the RS-232 serial port on the RoboRIO.
*
* The current implementation uses the VISA formatted I/O mode. This means that
* all traffic goes through the formatted buffers. This allows the intermingled
* use of print(), readString(), and the raw buffer accessors read() and
* write().
*
* More information can be found in the NI-VISA User Manual here:
* http://www.ni.com/pdf/manuals/370423a.pdf and the NI-VISA Programmer's
* Reference Manual here: http://www.ni.com/pdf/manuals/370132c.pdf
*/
public class SerialPort {
private byte m_port;
public enum Port {
kOnboard(0), kMXP(1), kUSB(2);
private int value;
private Port(int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
};
/**
* Represents the parity to use for serial communications
*/
public static class Parity {
/**
* The integer value representing this enumeration
*/
public final int value;
static final int kNone_val = 0;
static final int kOdd_val = 1;
static final int kEven_val = 2;
static final int kMark_val = 3;
static final int kSpace_val = 4;
/**
* parity: Use no parity
*/
public static final Parity kNone = new Parity(kNone_val);
/**
* parity: Use odd parity
*/
public static final Parity kOdd = new Parity(kOdd_val);
/**
* parity: Use even parity
*/
public static final Parity kEven = new Parity(kEven_val);
/**
* parity: Use mark parity
*/
public static final Parity kMark = new Parity(kMark_val);
/**
* parity: Use space parity
*/
public static final Parity kSpace = new Parity((kSpace_val));
private Parity(int value) {
this.value = value;
}
}
/**
* Represents the number of stop bits to use for Serial Communication
*/
public static class StopBits {
/**
* The integer value representing this enumeration
*/
public final int value;
static final int kOne_val = 10;
static final int kOnePointFive_val = 15;
static final int kTwo_val = 20;
/**
* stopBits: use 1
*/
public static final StopBits kOne = new StopBits(kOne_val);
/**
* stopBits: use 1.5
*/
public static final StopBits kOnePointFive = new StopBits(kOnePointFive_val);
/**
* stopBits: use 2
*/
public static final StopBits kTwo = new StopBits(kTwo_val);
private StopBits(int value) {
this.value = value;
}
}
/**
* Represents what type of flow control to use for serial communication
*/
public static class FlowControl {
/**
* The integer value representing this enumeration
*/
public final int value;
static final int kNone_val = 0;
static final int kXonXoff_val = 1;
static final int kRtsCts_val = 2;
static final int kDtrDsr_val = 4;
/**
* flowControl: use none
*/
public static final FlowControl kNone = new FlowControl(kNone_val);
/**
* flowcontrol: use on/off
*/
public static final FlowControl kXonXoff = new FlowControl(kXonXoff_val);
/**
* flowcontrol: use rts cts
*/
public static final FlowControl kRtsCts = new FlowControl(kRtsCts_val);
/**
* flowcontrol: use dts dsr
*/
public static final FlowControl kDtrDsr = new FlowControl(kDtrDsr_val);
private FlowControl(int value) {
this.value = value;
}
}
/**
* Represents which type of buffer mode to use when writing to a serial port
*/
public static class WriteBufferMode {
/**
* The integer value representing this enumeration
*/
public final int value;
static final int kFlushOnAccess_val = 1;
static final int kFlushWhenFull_val = 2;
/**
* Flush on access
*/
public static final WriteBufferMode kFlushOnAccess = new WriteBufferMode(kFlushOnAccess_val);
/**
* Flush when full
*/
public static final WriteBufferMode kFlushWhenFull = new WriteBufferMode(kFlushWhenFull_val);
private WriteBufferMode(int value) {
this.value = value;
}
}
/**
* Create an instance of a Serial Port class.
*
* @param baudRate The baud rate to configure the serial port.
* @param port The Serial port to use
* @param dataBits The number of data bits per transfer. Valid values are
* between 5 and 8 bits.
* @param parity Select the type of parity checking to use.
* @param stopBits The number of stop bits to use as defined by the enum
* StopBits.
*/
public SerialPort(final int baudRate, Port port, final int dataBits, Parity parity,
StopBits stopBits) {
m_port = (byte) port.getValue();
SerialPortJNI.serialInitializePort(m_port);
SerialPortJNI.serialSetBaudRate(m_port, baudRate);
SerialPortJNI.serialSetDataBits(m_port, (byte) dataBits);
SerialPortJNI.serialSetParity(m_port, (byte) parity.value);
SerialPortJNI.serialSetStopBits(m_port, (byte) stopBits.value);
// Set the default read buffer size to 1 to return bytes immediately
setReadBufferSize(1);
// Set the default timeout to 5 seconds.
setTimeout(5.0f);
// Don't wait until the buffer is full to transmit.
setWriteBufferMode(WriteBufferMode.kFlushOnAccess);
disableTermination();
UsageReporting.report(tResourceType.kResourceType_SerialPort, 0);
}
/**
* Create an instance of a Serial Port class. Defaults to one stop bit.
*
* @param baudRate The baud rate to configure the serial port.
* @param dataBits The number of data bits per transfer. Valid values are
* between 5 and 8 bits.
* @param parity Select the type of parity checking to use.
*/
public SerialPort(final int baudRate, Port port, final int dataBits, Parity parity) {
this(baudRate, port, dataBits, parity, StopBits.kOne);
}
/**
* Create an instance of a Serial Port class. Defaults to no parity and one
* stop bit.
*
* @param baudRate The baud rate to configure the serial port.
* @param dataBits The number of data bits per transfer. Valid values are
* between 5 and 8 bits.
*/
public SerialPort(final int baudRate, Port port, final int dataBits) {
this(baudRate, port, dataBits, Parity.kNone, StopBits.kOne);
}
/**
* Create an instance of a Serial Port class. Defaults to 8 databits, no
* parity, and one stop bit.
*
* @param baudRate The baud rate to configure the serial port.
*/
public SerialPort(final int baudRate, Port port) {
this(baudRate, port, 8, Parity.kNone, StopBits.kOne);
}
/**
* Destructor.
*/
public void free() {
SerialPortJNI.serialClose(m_port);
}
/**
* Set the type of flow control to enable on this port.
*
* By default, flow control is disabled.
*$
* @param flowControl the FlowControl value to use
*/
public void setFlowControl(FlowControl flowControl) {
SerialPortJNI.serialSetFlowControl(m_port, (byte) flowControl.value);
}
/**
* Enable termination and specify the termination character.
*
* Termination is currently only implemented for receive. When the the
* terminator is received, the read() or readString() will return fewer bytes
* than requested, stopping after the terminator.
*
* @param terminator The character to use for termination.
*/
public void enableTermination(char terminator) {
SerialPortJNI.serialEnableTermination(m_port, terminator);
}
/**
* Enable termination with the default terminator '\n'
*
* Termination is currently only implemented for receive. When the the
* terminator is received, the read() or readString() will return fewer bytes
* than requested, stopping after the terminator.
*
* The default terminator is '\n'
*/
public void enableTermination() {
this.enableTermination('\n');
}
/**
* Disable termination behavior.
*/
public void disableTermination() {
SerialPortJNI.serialDisableTermination(m_port);
}
/**
* Get the number of bytes currently available to read from the serial port.
*
* @return The number of bytes available to read.
*/
public int getBytesReceived() {
return SerialPortJNI.serialGetBytesRecieved(m_port);
}
/**
* Read a string out of the buffer. Reads the entire contents of the buffer
*
* @return The read string
*/
public String readString() {
return readString(getBytesReceived());
}
/**
* Read a string out of the buffer. Reads the entire contents of the buffer
*
* @param count the number of characters to read into the string
* @return The read string
*/
public String readString(int count) {
byte[] out = read(count);
try {
return new String(out, 0, count, "US-ASCII");
} catch (UnsupportedEncodingException ex) {
ex.printStackTrace();
return new String();
}
}
/**
* Read raw bytes out of the buffer.
*
* @param count The maximum number of bytes to read.
* @return An array of the read bytes
*/
public byte[] read(final int count) {
ByteBuffer dataReceivedBuffer = ByteBuffer.allocateDirect(count);
int gotten = SerialPortJNI.serialRead(m_port, dataReceivedBuffer, count);
byte[] retVal = new byte[gotten];
dataReceivedBuffer.get(retVal);
return retVal;
}
/**
* Write raw bytes to the serial port.
*
* @param buffer The buffer of bytes to write.
* @param count The maximum number of bytes to write.
* @return The number of bytes actually written into the port.
*/
public int write(byte[] buffer, int count) {
ByteBuffer dataToSendBuffer = ByteBuffer.allocateDirect(count);
dataToSendBuffer.put(buffer, 0, count);
return SerialPortJNI.serialWrite(m_port, dataToSendBuffer, count);
}
/**
* Write a string to the serial port
*
* @param data The string to write to the serial port.
* @return The number of bytes actually written into the port.
*/
public int writeString(String data) {
return write(data.getBytes(), data.length());
}
/**
* Configure the timeout of the serial port.
*
* This defines the timeout for transactions with the hardware. It will affect
* reads if less bytes are available than the read buffer size (defaults to 1)
* and very large writes.
*
* @param timeout The number of seconds to to wait for I/O.
*/
public void setTimeout(double timeout) {
SerialPortJNI.serialSetTimeout(m_port, (float) timeout);
}
/**
* Specify the size of the input buffer.
*
* Specify the amount of data that can be stored before data from the device
* is returned to Read. If you want data that is received to be returned
* immediately, set this to 1.
*
* It the buffer is not filled before the read timeout expires, all data that
* has been received so far will be returned.
*
* @param size The read buffer size.
*/
public void setReadBufferSize(int size) {
SerialPortJNI.serialSetReadBufferSize(m_port, size);
}
/**
* Specify the size of the output buffer.
*
* Specify the amount of data that can be stored before being transmitted to
* the device.
*
* @param size The write buffer size.
*/
public void setWriteBufferSize(int size) {
SerialPortJNI.serialSetWriteBufferSize(m_port, size);
}
/**
* Specify the flushing behavior of the output buffer.
*
* When set to kFlushOnAccess, data is synchronously written to the serial
* port after each call to either print() or write().
*
* When set to kFlushWhenFull, data will only be written to the serial port
* when the buffer is full or when flush() is called.
*
* @param mode The write buffer mode.
*/
public void setWriteBufferMode(WriteBufferMode mode) {
SerialPortJNI.serialSetWriteMode(m_port, (byte) mode.value);
}
/**
* Force the output buffer to be written to the port.
*
* This is used when setWriteBufferMode() is set to kFlushWhenFull to force a
* flush before the buffer is full.
*/
public void flush() {
SerialPortJNI.serialFlush(m_port);
}
/**
* Reset the serial port driver to a known state.
*
* Empty the transmit and receive buffers in the device and formatted I/O.
*/
public void reset() {
SerialPortJNI.serialClear(m_port);
}
}

View File

@@ -0,0 +1,171 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType;
import edu.wpi.first.wpilibj.communication.UsageReporting;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import edu.wpi.first.wpilibj.tables.ITable;
import edu.wpi.first.wpilibj.tables.ITableListener;
/**
* Standard hobby style servo.
*
* The range parameters default to the appropriate values for the Hitec HS-322HD
* servo provided in the FIRST Kit of Parts in 2008.
*/
public class Servo extends PWM {
private static final double kMaxServoAngle = 180.0;
private static final double kMinServoAngle = 0.0;
protected static final double kDefaultMaxServoPWM = 2.4;
protected static final double kDefaultMinServoPWM = .6;
/**
* Common initialization code called by all constructors.
*
* InitServo() assigns defaults for the period multiplier for the servo PWM
* control signal, as well as the minimum and maximum PWM values supported by
* the servo.
*
*/
private void initServo() {
setBounds(kDefaultMaxServoPWM, 0, 0, 0, kDefaultMinServoPWM);
setPeriodMultiplier(PeriodMultiplier.k4X);
LiveWindow.addActuator("Servo", getChannel(), this);
UsageReporting.report(tResourceType.kResourceType_Servo, getChannel());
}
/**
* Constructor.<br>
*
* By default {@value #kDefaultMaxServoPWM} ms is used as the maxPWM value<br>
* By default {@value #kDefaultMinServoPWM} ms is used as the minPWM value<br>
*
* @param channel The PWM channel to which the servo is attached. 0-9 are
* on-board, 10-19 are on the MXP port
*/
public Servo(final int channel) {
super(channel);
initServo();
}
/**
* Set the servo position.
*
* Servo values range from 0.0 to 1.0 corresponding to the range of full left
* to full right.
*
* @param value Position from 0.0 to 1.0.
*/
public void set(double value) {
setPosition(value);
}
/**
* Get the servo position.
*
* Servo values range from 0.0 to 1.0 corresponding to the range of full left
* to full right.
*
* @return Position from 0.0 to 1.0.
*/
public double get() {
return getPosition();
}
/**
* Set the servo angle.
*
* Assume that the servo angle is linear with respect to the PWM value (big
* assumption, need to test).
*
* Servo angles that are out of the supported range of the servo simply
* "saturate" in that direction In other words, if the servo has a range of (X
* degrees to Y degrees) than angles of less than X result in an angle of X
* being set and angles of more than Y degrees result in an angle of Y being
* set.
*
* @param degrees The angle in degrees to set the servo.
*/
public void setAngle(double degrees) {
if (degrees < kMinServoAngle) {
degrees = kMinServoAngle;
} else if (degrees > kMaxServoAngle) {
degrees = kMaxServoAngle;
}
setPosition(((degrees - kMinServoAngle)) / getServoAngleRange());
}
/**
* Get the servo angle.
*
* Assume that the servo angle is linear with respect to the PWM value (big
* assumption, need to test).
*$
* @return The angle in degrees to which the servo is set.
*/
public double getAngle() {
return getPosition() * getServoAngleRange() + kMinServoAngle;
}
private double getServoAngleRange() {
return kMaxServoAngle - kMinServoAngle;
}
/*
* Live Window code, only does anything if live window is activated.
*/
public String getSmartDashboardType() {
return "Servo";
}
private ITable m_table;
private ITableListener m_table_listener;
/**
* {@inheritDoc}
*/
public void initTable(ITable subtable) {
m_table = subtable;
updateTable();
}
/**
* {@inheritDoc}
*/
public void updateTable() {
if (m_table != null) {
m_table.putNumber("Value", get());
}
}
/**
* {@inheritDoc}
*/
public void startLiveWindowMode() {
m_table_listener = new ITableListener() {
public void valueChanged(ITable itable, String key, Object value, boolean bln) {
set(((Double) value).doubleValue());
}
};
m_table.addTableListener("Value", m_table_listener, true);
}
/**
* {@inheritDoc}
*/
public void stopLiveWindowMode() {
// TODO: Broken, should only remove the listener from "Value" only.
m_table.removeTableListener(m_table_listener);
}
}

View File

@@ -0,0 +1,167 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType;
import edu.wpi.first.wpilibj.communication.UsageReporting;
import edu.wpi.first.wpilibj.hal.SolenoidJNI;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable;
import edu.wpi.first.wpilibj.tables.ITable;
import edu.wpi.first.wpilibj.tables.ITableListener;
import edu.wpi.first.wpilibj.util.AllocationException;
import edu.wpi.first.wpilibj.util.CheckedAllocationException;
/**
* Solenoid class for running high voltage Digital Output.
*
* The Solenoid class is typically used for pneumatics solenoids, but could be
* used for any device within the current spec of the PCM.
*/
public class Solenoid extends SolenoidBase implements LiveWindowSendable {
private int m_channel; // /< The channel to control.
private long m_solenoid_port;
/**
* Common function to implement constructor behavior.
*/
private synchronized void initSolenoid() {
checkSolenoidModule(m_moduleNumber);
checkSolenoidChannel(m_channel);
long port = SolenoidJNI.getPortWithModule((byte) m_moduleNumber, (byte) m_channel);
m_solenoid_port = SolenoidJNI.initializeSolenoidPort(port);
LiveWindow.addActuator("Solenoid", m_moduleNumber, m_channel, this);
UsageReporting.report(tResourceType.kResourceType_Solenoid, m_channel, m_moduleNumber);
}
/**
* Constructor using the default PCM ID (0)
*
* @param channel The channel on the PCM to control (0..7).
*/
public Solenoid(final int channel) {
super(getDefaultSolenoidModule());
m_channel = channel;
initSolenoid();
}
/**
* Constructor.
*
* @param moduleNumber The CAN ID of the PCM the solenoid is attached to.
* @param channel The channel on the PCM to control (0..7).
*/
public Solenoid(final int moduleNumber, final int channel) {
super(moduleNumber);
m_channel = channel;
initSolenoid();
}
/**
* Destructor.
*/
public synchronized void free() {
// m_allocated.free((m_moduleNumber - 1) * kSolenoidChannels + m_channel -
// 1);
}
/**
* Set the value of a solenoid.
*
* @param on Turn the solenoid output off or on.
*/
public void set(boolean on) {
byte value = (byte) (on ? 0xFF : 0x00);
byte mask = (byte) (1 << m_channel);
set(value, mask);
}
/**
* Read the current value of the solenoid.
*
* @return The current value of the solenoid.
*/
public boolean get() {
int value = getAll() & (1 << m_channel);
return (value != 0);
}
/**
* Check if solenoid is blacklisted. If a solenoid is shorted, it is added to
* the blacklist and disabled until power cycle, or until faults are cleared.
*
* @see clearAllPCMStickyFaults()
*
* @return If solenoid is disabled due to short.
*/
public boolean isBlackListed() {
int value = getPCMSolenoidBlackList() & (1 << m_channel);
return (value != 0);
}
/*
* Live Window code, only does anything if live window is activated.
*/
public String getSmartDashboardType() {
return "Solenoid";
}
private ITable m_table;
private ITableListener m_table_listener;
/**
* {@inheritDoc}
*/
public void initTable(ITable subtable) {
m_table = subtable;
updateTable();
}
/**
* {@inheritDoc}
*/
public ITable getTable() {
return m_table;
}
/**
* {@inheritDoc}
*/
public void updateTable() {
if (m_table != null) {
m_table.putBoolean("Value", get());
}
}
/**
* {@inheritDoc}
*/
public void startLiveWindowMode() {
set(false); // Stop for safety
m_table_listener = new ITableListener() {
public void valueChanged(ITable itable, String key, Object value, boolean bln) {
set(((Boolean) value).booleanValue());
}
};
m_table.addTableListener("Value", m_table_listener, true);
}
/**
* {@inheritDoc}
*/
public void stopLiveWindowMode() {
set(false); // Stop for safety
// TODO: Broken, should only remove the listener from "Value" only.
m_table.removeTableListener(m_table_listener);
}
}

View File

@@ -0,0 +1,107 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import edu.wpi.first.wpilibj.hal.SolenoidJNI;
/**
* SolenoidBase class is the common base class for the Solenoid and
* DoubleSolenoid classes.
*/
public abstract class SolenoidBase extends SensorBase {
private long[] m_ports;
protected int m_moduleNumber; // /< The number of the solenoid module being
// used.
protected Resource m_allocated = new Resource(63 * SensorBase.kSolenoidChannels);
/**
* Constructor.
*
* @param moduleNumber The PCM CAN ID
*/
public SolenoidBase(final int moduleNumber) {
m_moduleNumber = moduleNumber;
m_ports = new long[SensorBase.kSolenoidChannels];
for (int i = 0; i < SensorBase.kSolenoidChannels; i++) {
long port = SolenoidJNI.getPortWithModule((byte) moduleNumber, (byte) i);
m_ports[i] = SolenoidJNI.initializeSolenoidPort(port);
}
}
/**
* Set the value of a solenoid.
*
* @param value The value you want to set on the module.
* @param mask The channels you want to be affected.
*/
protected synchronized void set(int value, int mask) {
for (int i = 0; i < SensorBase.kSolenoidChannels; i++) {
int local_mask = 1 << i;
if ((mask & local_mask) != 0)
SolenoidJNI.setSolenoid(m_ports[i], (value & local_mask) != 0);
}
}
/**
* Read all 8 solenoids from the module used by this solenoid as a single byte
*
* @return The current value of all 8 solenoids on this module.
*/
public byte getAll() {
byte value = 0;
for (int i = 0; i < SensorBase.kSolenoidChannels; i++) {
value |= (SolenoidJNI.getSolenoid(m_ports[i]) ? 1 : 0) << i;
}
return value;
}
/**
* Reads complete solenoid blacklist for all 8 solenoids as a single byte.
*$
* If a solenoid is shorted, it is added to the blacklist and disabled until
* power cycle, or until faults are cleared.
*
* @see #clearAllPCMStickyFaults()
*$
* @return The solenoid blacklist of all 8 solenoids on the module.
*/
public byte getPCMSolenoidBlackList() {
return (byte)SolenoidJNI.getPCMSolenoidBlackList(m_ports[0]);
}
/**
* @return true if PCM sticky fault is set : The common highside solenoid
* voltage rail is too low, most likely a solenoid channel is shorted.
*/
public boolean getPCMSolenoidVoltageStickyFault() {
return SolenoidJNI.getPCMSolenoidVoltageStickyFault(m_ports[0]);
}
/**
* @return true if PCM is in fault state : The common highside solenoid
* voltage rail is too low, most likely a solenoid channel is shorted.
*/
public boolean getPCMSolenoidVoltageFault() {
return SolenoidJNI.getPCMSolenoidVoltageFault(m_ports[0]);
}
/**
* Clear ALL sticky faults inside PCM that Compressor is wired to.
*
* If a sticky fault is set, then it will be persistently cleared. Compressor
* drive maybe momentarily disable while flags are being cleared. Care should
* be taken to not call this too frequently, otherwise normal compressor
* functionality may be prevented.
*
* If no sticky faults are set then this call will have no effect.
*/
public void clearAllPCMStickyFaults() {
SolenoidJNI.clearAllPCMStickyFaults(m_ports[0]);
}
}

View File

@@ -0,0 +1,60 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
/**
* Interface for speed controlling devices.
*/
public interface SpeedController extends PIDOutput {
/**
* Common interface for getting the current set speed of a speed controller.
*
* @return The current set speed. Value is between -1.0 and 1.0.
*/
double get();
/**
* Common interface for setting the speed of a speed controller.
*
* @param speed The speed to set. Value should be between -1.0 and 1.0.
* @param syncGroup The update group to add this Set() to, pending
* UpdateSyncGroup(). If 0, update immediately.
*/
void set(double speed, byte syncGroup);
/**
* Common interface for setting the speed of a speed controller.
*
* @param speed The speed to set. Value should be between -1.0 and 1.0.
*/
void set(double speed);
/**
* Common interface for inverting direction of a speed controller.
*
* @param isInverted The state of inversion true is inverted.
*/
void setInverted(boolean isInverted);
/**
* Common interface for returning if a speed controller is in the inverted
* state or not.
*$
* @return isInverted The state of the inversion true is inverted.
*
*/
boolean getInverted();
/**
* Disable the speed controller
*/
void disable();
}

View File

@@ -0,0 +1,124 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType;
import edu.wpi.first.wpilibj.communication.UsageReporting;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
/**
* Cross the Road Electronics (CTRE) Talon and Talon SR Speed Controller
*/
public class Talon extends SafePWM implements SpeedController {
private boolean isInverted = false;
/**
* Common initialization code called by all constructors.
*
* Note that the Talon uses the following bounds for PWM values. These values
* should work reasonably well for most controllers, but if users experience
* issues such as asymmetric behavior around the deadband or inability to
* saturate the controller in either direction, calibration is recommended.
* The calibration procedure can be found in the Talon User Manual available
* from CTRE.
*
* - 2.037ms = full "forward" - 1.539ms = the "high end" of the deadband range
* - 1.513ms = center of the deadband range (off) - 1.487ms = the "low end" of
* the deadband range - .989ms = full "reverse"
*/
private void initTalon() {
setBounds(2.037, 1.539, 1.513, 1.487, .989);
setPeriodMultiplier(PeriodMultiplier.k1X);
setRaw(m_centerPwm);
setZeroLatch();
LiveWindow.addActuator("Talon", getChannel(), this);
UsageReporting.report(tResourceType.kResourceType_Talon, getChannel());
}
/**
* Constructor for a Talon (original or Talon SR)
*
* @param channel The PWM channel that the Talon is attached to. 0-9 are
* on-board, 10-19 are on the MXP port
*/
public Talon(final int channel) {
super(channel);
initTalon();
}
/**
* Set the PWM value.
*
* @deprecated For compatibility with CANJaguar
*
* The PWM value is set using a range of -1.0 to 1.0,
* appropriately scaling the value for the FPGA.
*
* @param speed The speed to set. Value should be between -1.0 and 1.0.
* @param syncGroup The update group to add this Set() to, pending
* UpdateSyncGroup(). If 0, update immediately.
*/
public void set(double speed, byte syncGroup) {
setSpeed(isInverted ? -speed : speed);
Feed();
}
/**
* Set the PWM value.
*
* The PWM value is set using a range of -1.0 to 1.0, appropriately scaling
* the value for the FPGA.
*
* @param speed The speed value between -1.0 and 1.0 to set.
*/
public void set(double speed) {
setSpeed(isInverted ? -speed : speed);
Feed();
}
/**
* Common interface for inverting direction of a speed controller
*
* @param isInverted The state of inversion true is inverted
*/
@Override
public void setInverted(boolean isInverted) {
this.isInverted = isInverted;
}
/**
* Common interface for the inverting direction of a speed controller.
*
* @return isInverted The state of inversion, true is inverted.
*
*/
@Override
public boolean getInverted() {
return this.isInverted;
}
/**
* Get the recently set value of the PWM.
*
* @return The most recently set value for the PWM between -1.0 and 1.0.
*/
public double get() {
return getSpeed();
}
/**
* Write out the PID value as seen in the PIDOutput base object.
*
* @param output Write out the PWM value as was found in the PIDController
*/
public void pidWrite(double output) {
set(output);
}
}

View File

@@ -0,0 +1,125 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType;
import edu.wpi.first.wpilibj.communication.UsageReporting;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
/**
* Cross the Road Electronics (CTRE) Talon SRX Speed Controller with PWM control
*$
* @see CANTalon CANTalon for CAN control of Talon SRX
*/
public class TalonSRX extends SafePWM implements SpeedController {
private boolean isInverted = false;
/**
* Common initialization code called by all constructors.
*
* Note that the TalonSRX uses the following bounds for PWM values. These
* values should work reasonably well for most controllers, but if users
* experience issues such as asymmetric behavior around the deadband or
* inability to saturate the controller in either direction, calibration is
* recommended. The calibration procedure can be found in the TalonSRX User
* Manual available from CTRE.
*
* - 2.0004ms = full "forward" - 1.52ms = the "high end" of the deadband range
* - 1.50ms = center of the deadband range (off) - 1.48ms = the "low end" of
* the deadband range - .997ms = full "reverse"
*/
protected void initTalonSRX() {
setBounds(2.004, 1.52, 1.50, 1.48, .997);
setPeriodMultiplier(PeriodMultiplier.k1X);
setRaw(m_centerPwm);
setZeroLatch();
LiveWindow.addActuator("TalonSRX", getChannel(), this);
UsageReporting.report(tResourceType.kResourceType_TalonSRX, getChannel());
}
/**
* Constructor for a TalonSRX connected via PWM
*
* @param channel The PWM channel that the TalonSRX is attached to. 0-9 are
* on-board, 10-19 are on the MXP port
*/
public TalonSRX(final int channel) {
super(channel);
initTalonSRX();
}
/**
* Set the PWM value.
*
* @deprecated For compatibility with CANJaguar
*
* The PWM value is set using a range of -1.0 to 1.0,
* appropriately scaling the value for the FPGA.
*
* @param speed The speed to set. Value should be between -1.0 and 1.0.
* @param syncGroup The update group to add this Set() to, pending
* UpdateSyncGroup(). If 0, update immediately.
*/
public void set(double speed, byte syncGroup) {
setSpeed(isInverted ? -speed : speed);
Feed();
}
/**
* Set the PWM value.
*
* The PWM value is set using a range of -1.0 to 1.0, appropriately scaling
* the value for the FPGA.
*
* @param speed The speed value between -1.0 and 1.0 to set.
*/
public void set(double speed) {
setSpeed(isInverted ? -speed : speed);
Feed();
}
/**
* Common interface for inverting direction of a speed controller.
*
* @param isInverted The state of inversion, true is inverted.
*/
@Override
public void setInverted(boolean isInverted) {
this.isInverted = isInverted;
}
/**
* Common interface for the inverting direction of a speed controller.
*
* @return isInverted The state of inversion, true is inverted.
*
*/
@Override
public boolean getInverted() {
return this.isInverted;
}
/**
* Get the recently set value of the PWM.
*
* @return The most recently set value for the PWM between -1.0 and 1.0.
*/
public double get() {
return getSpeed();
}
/**
* Write out the PID value as seen in the PIDOutput base object.
*
* @param output Write out the PWM value as was found in the PIDController
*/
public void pidWrite(double output) {
set(output);
}
}

View File

@@ -0,0 +1,449 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType;
import edu.wpi.first.wpilibj.communication.UsageReporting;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable;
import edu.wpi.first.wpilibj.tables.ITable;
/**
* Ultrasonic rangefinder class. The Ultrasonic rangefinder measures absolute
* distance based on the round-trip time of a ping generated by the controller.
* These sensors use two transducers, a speaker and a microphone both tuned to
* the ultrasonic range. A common ultrasonic sensor, the Daventech SRF04
* requires a short pulse to be generated on a digital channel. This causes the
* chirp to be emmitted. A second line becomes high as the ping is transmitted
* and goes low when the echo is received. The time that the line is high
* determines the round trip distance (time of flight).
*/
public class Ultrasonic extends SensorBase implements PIDSource, LiveWindowSendable {
/**
* The units to return when PIDGet is called
*/
public static enum Unit {
/**
* Use inches for PIDGet
*/
kInches,
/**
* Use millimeters for PIDGet
*/
kMillimeters
}
private static final double kPingTime = 10 * 1e-6; // /< Time (sec) for the
// ping trigger pulse.
private static final int kPriority = 90; // /< Priority that the ultrasonic
// round robin task runs.
private static final double kMaxUltrasonicTime = 0.1; // /< Max time (ms)
// between readings.
private static final double kSpeedOfSoundInchesPerSec = 1130.0 * 12.0;
private static Ultrasonic m_firstSensor = null; // head of the ultrasonic
// sensor list
private static boolean m_automaticEnabled = false; // automatic round robin
// mode
private DigitalInput m_echoChannel = null;
private DigitalOutput m_pingChannel = null;
private boolean m_allocatedChannels;
private boolean m_enabled = false;
private Counter m_counter = null;
private Ultrasonic m_nextSensor = null;
private static Thread m_task = null; // task doing the round-robin automatic
// sensing
private Unit m_units;
private static int m_instances = 0;
protected PIDSourceType m_pidSource = PIDSourceType.kDisplacement;
/**
* Background task that goes through the list of ultrasonic sensors and pings
* each one in turn. The counter is configured to read the timing of the
* returned echo pulse.
*
* DANGER WILL ROBINSON, DANGER WILL ROBINSON: This code runs as a task and
* assumes that none of the ultrasonic sensors will change while it's running.
* If one does, then this will certainly break. Make sure to disable automatic
* mode before changing anything with the sensors!!
*/
private class UltrasonicChecker extends Thread {
public synchronized void run() {
Ultrasonic u = null;
while (m_automaticEnabled) {
if (u == null) {
u = m_firstSensor;
}
if (u == null) {
return;
}
if (u.isEnabled()) {
u.m_pingChannel.pulse(m_pingChannel.m_channel, (float) kPingTime); // do
// the
// ping
}
u = u.m_nextSensor;
Timer.delay(.1); // wait for ping to return
}
}
}
/**
* Initialize the Ultrasonic Sensor. This is the common code that initializes
* the ultrasonic sensor given that there are two digital I/O channels
* allocated. If the system was running in automatic mode (round robin) when
* the new sensor is added, it is stopped, the sensor is added, then automatic
* mode is restored.
*/
private synchronized void initialize() {
if (m_task == null) {
m_task = new UltrasonicChecker();
}
boolean originalMode = m_automaticEnabled;
setAutomaticMode(false); // kill task when adding a new sensor
m_nextSensor = m_firstSensor;
m_firstSensor = this;
m_counter = new Counter(m_echoChannel); // set up counter for this
// sensor
m_counter.setMaxPeriod(1.0);
m_counter.setSemiPeriodMode(true);
m_counter.reset();
m_enabled = true; // make it available for round robin scheduling
setAutomaticMode(originalMode);
m_instances++;
UsageReporting.report(tResourceType.kResourceType_Ultrasonic, m_instances);
LiveWindow.addSensor("Ultrasonic", m_echoChannel.getChannel(), this);
}
/**
* Create an instance of the Ultrasonic Sensor. This is designed to supchannel
* the Daventech SRF04 and Vex ultrasonic sensors.
*
* @param pingChannel The digital output channel that sends the pulse to
* initiate the sensor sending the ping.
* @param echoChannel The digital input channel that receives the echo. The
* length of time that the echo is high represents the round trip time
* of the ping, and the distance.
* @param units The units returned in either kInches or kMilliMeters
*/
public Ultrasonic(final int pingChannel, final int echoChannel, Unit units) {
m_pingChannel = new DigitalOutput(pingChannel);
m_echoChannel = new DigitalInput(echoChannel);
m_allocatedChannels = true;
m_units = units;
initialize();
}
/**
* Create an instance of the Ultrasonic Sensor. This is designed to supchannel
* the Daventech SRF04 and Vex ultrasonic sensors. Default unit is inches.
*
* @param pingChannel The digital output channel that sends the pulse to
* initiate the sensor sending the ping.
* @param echoChannel The digital input channel that receives the echo. The
* length of time that the echo is high represents the round trip time
* of the ping, and the distance.
*/
public Ultrasonic(final int pingChannel, final int echoChannel) {
this(pingChannel, echoChannel, Unit.kInches);
}
/**
* Create an instance of an Ultrasonic Sensor from a DigitalInput for the echo
* channel and a DigitalOutput for the ping channel.
*
* @param pingChannel The digital output object that starts the sensor doing a
* ping. Requires a 10uS pulse to start.
* @param echoChannel The digital input object that times the return pulse to
* determine the range.
* @param units The units returned in either kInches or kMilliMeters
*/
public Ultrasonic(DigitalOutput pingChannel, DigitalInput echoChannel, Unit units) {
if (pingChannel == null || echoChannel == null) {
throw new NullPointerException("Null Channel Provided");
}
m_allocatedChannels = false;
m_pingChannel = pingChannel;
m_echoChannel = echoChannel;
m_units = units;
initialize();
}
/**
* Create an instance of an Ultrasonic Sensor from a DigitalInput for the echo
* channel and a DigitalOutput for the ping channel. Default unit is inches.
*
* @param pingChannel The digital output object that starts the sensor doing a
* ping. Requires a 10uS pulse to start.
* @param echoChannel The digital input object that times the return pulse to
* determine the range.
*/
public Ultrasonic(DigitalOutput pingChannel, DigitalInput echoChannel) {
this(pingChannel, echoChannel, Unit.kInches);
}
/**
* Destructor for the ultrasonic sensor. Delete the instance of the ultrasonic
* sensor by freeing the allocated digital channels. If the system was in
* automatic mode (round robin), then it is stopped, then started again after
* this sensor is removed (provided this wasn't the last sensor).
*/
public synchronized void free() {
boolean wasAutomaticMode = m_automaticEnabled;
setAutomaticMode(false);
if (m_allocatedChannels) {
if (m_pingChannel != null) {
m_pingChannel.free();
}
if (m_echoChannel != null) {
m_echoChannel.free();
}
}
if (m_counter != null) {
m_counter.free();
m_counter = null;
}
m_pingChannel = null;
m_echoChannel = null;
if (this == m_firstSensor) {
m_firstSensor = m_nextSensor;
if (m_firstSensor == null) {
setAutomaticMode(false);
}
} else {
for (Ultrasonic s = m_firstSensor; s != null; s = s.m_nextSensor) {
if (this == s.m_nextSensor) {
s.m_nextSensor = s.m_nextSensor.m_nextSensor;
break;
}
}
}
if (m_firstSensor != null && wasAutomaticMode) {
setAutomaticMode(true);
}
}
/**
* Turn Automatic mode on/off. When in Automatic mode, all sensors will fire
* in round robin, waiting a set time between each sensor.
*
* @param enabling Set to true if round robin scheduling should start for all
* the ultrasonic sensors. This scheduling method assures that the
* sensors are non-interfering because no two sensors fire at the same
* time. If another scheduling algorithm is preffered, it can be
* implemented by pinging the sensors manually and waiting for the
* results to come back.
*/
public void setAutomaticMode(boolean enabling) {
if (enabling == m_automaticEnabled) {
return; // ignore the case of no change
}
m_automaticEnabled = enabling;
if (enabling) {
// enabling automatic mode.
// Clear all the counters so no data is valid
for (Ultrasonic u = m_firstSensor; u != null; u = u.m_nextSensor) {
u.m_counter.reset();
}
// Start round robin task
m_task.start();
} else {
// disabling automatic mode. Wait for background task to stop
// running.
while (m_task.isAlive()) {
Timer.delay(.15); // just a little longer than the ping time for
// round-robin to stop
}
// clear all the counters (data now invalid) since automatic mode is
// stopped
for (Ultrasonic u = m_firstSensor; u != null; u = u.m_nextSensor) {
u.m_counter.reset();
}
}
}
/**
* Single ping to ultrasonic sensor. Send out a single ping to the ultrasonic
* sensor. This only works if automatic (round robin) mode is disabled. A
* single ping is sent out, and the counter should count the semi-period when
* it comes in. The counter is reset to make the current value invalid.
*/
public void ping() {
setAutomaticMode(false); // turn off automatic round robin if pinging
// single sensor
m_counter.reset(); // reset the counter to zero (invalid data now)
m_pingChannel.pulse(m_pingChannel.m_channel, (float) kPingTime); // do
// the
// ping
// to
// start
// getting
// a
// single
// range
}
/**
* Check if there is a valid range measurement. The ranges are accumulated in
* a counter that will increment on each edge of the echo (return) signal. If
* the count is not at least 2, then the range has not yet been measured, and
* is invalid.
*
* @return true if the range is valid
*/
public boolean isRangeValid() {
return m_counter.get() > 1;
}
/**
* Get the range in inches from the ultrasonic sensor.
*
* @return double Range in inches of the target returned from the ultrasonic
* sensor. If there is no valid value yet, i.e. at least one
* measurement hasn't completed, then return 0.
*/
public double getRangeInches() {
if (isRangeValid()) {
return m_counter.getPeriod() * kSpeedOfSoundInchesPerSec / 2.0;
} else {
return 0;
}
}
/**
* Get the range in millimeters from the ultrasonic sensor.
*
* @return double Range in millimeters of the target returned by the
* ultrasonic sensor. If there is no valid value yet, i.e. at least
* one measurement hasn't complted, then return 0.
*/
public double getRangeMM() {
return getRangeInches() * 25.4;
}
/**
* {@inheritDoc}
*/
public void setPIDSourceType(PIDSourceType pidSource) {
if (!pidSource.equals(PIDSourceType.kDisplacement)) {
throw new IllegalArgumentException("Only displacement PID is allowed for potentiometers.");
}
m_pidSource = pidSource;
}
/**
* {@inheritDoc}
*/
public PIDSourceType getPIDSourceType() {
return m_pidSource;
}
/**
* Get the range in the current DistanceUnit for the PIDSource base object.
*
* @return The range in DistanceUnit
*/
public double pidGet() {
switch (m_units) {
case kInches:
return getRangeInches();
case kMillimeters:
return getRangeMM();
default:
return 0.0;
}
}
/**
* Set the current DistanceUnit that should be used for the PIDSource base
* object.
*
* @param units The DistanceUnit that should be used.
*/
public void setDistanceUnits(Unit units) {
m_units = units;
}
/**
* Get the current DistanceUnit that is used for the PIDSource base object.
*
* @return The type of DistanceUnit that is being used.
*/
public Unit getDistanceUnits() {
return m_units;
}
/**
* Is the ultrasonic enabled
*
* @return true if the ultrasonic is enabled
*/
public boolean isEnabled() {
return m_enabled;
}
/**
* Set if the ultrasonic is enabled
*
* @param enable set to true to enable the ultrasonic
*/
public void setEnabled(boolean enable) {
m_enabled = enable;
}
/*
* Live Window code, only does anything if live window is activated.
*/
public String getSmartDashboardType() {
return "Ultrasonic";
}
private ITable m_table;
/**
* {@inheritDoc}
*/
public void initTable(ITable subtable) {
m_table = subtable;
updateTable();
}
/**
* {@inheritDoc}
*/
public ITable getTable() {
return m_table;
}
/**
* {@inheritDoc}
*/
public void updateTable() {
if (m_table != null) {
m_table.putNumber("Value", getRangeInches());
}
}
/**
* {@inheritDoc}
*/
public void startLiveWindowMode() {}
/**
* {@inheritDoc}
*/
public void stopLiveWindowMode() {}
}

View File

@@ -0,0 +1,56 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import edu.wpi.first.wpilibj.hal.HALUtil;
/**
* Contains global utility functions
*/
public class Utility {
private Utility() {}
/**
* Return the FPGA Version number. For now, expect this to be 2009.
*
* @return FPGA Version number.
*/
int getFPGAVersion() {
return HALUtil.getFPGAVersion();
}
/**
* Return the FPGA Revision number. The format of the revision is 3 numbers.
* The 12 most significant bits are the Major Revision. the next 8 bits are
* the Minor Revision. The 12 least significant bits are the Build Number.
*
* @return FPGA Revision number.
*/
long getFPGARevision() {
return (long) HALUtil.getFPGARevision();
}
/**
* Read the microsecond timer from the FPGA.
*
* @return The current time in microseconds according to the FPGA.
*/
public static long getFPGATime() {
return HALUtil.getFPGATime();
}
/**
* Get the state of the "USER" button on the RoboRIO
*$
* @return true if the button is currently pressed down
*/
public static boolean getUserButton() {
return HALUtil.getFPGAButton();
}
}

View File

@@ -0,0 +1,128 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType;
import edu.wpi.first.wpilibj.communication.UsageReporting;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
/**
* VEX Robotics Victor 888 Speed Controller
*$
* The Vex Robotics Victor 884 Speed Controller can also be used with this class
* but may need to be calibrated per the Victor 884 user manual.
*/
public class Victor extends SafePWM implements SpeedController {
private boolean isInverted = false;
/**
* Common initialization code called by all constructors.
*
* Note that the Victor uses the following bounds for PWM values. These values
* were determined empirically and optimized for the Victor 888. These values
* should work reasonably well for Victor 884 controllers also but if users
* experience issues such as asymmetric behaviour around the deadband or
* inability to saturate the controller in either direction, calibration is
* recommended. The calibration procedure can be found in the Victor 884 User
* Manual available from VEX Robotics:
* http://content.vexrobotics.com/docs/ifi-v884-users-manual-9-25-06.pdf
*
* - 2.027ms = full "forward" - 1.525ms = the "high end" of the deadband range
* - 1.507ms = center of the deadband range (off) - 1.49ms = the "low end" of
* the deadband range - 1.026ms = full "reverse"
*/
private void initVictor() {
setBounds(2.027, 1.525, 1.507, 1.49, 1.026);
setPeriodMultiplier(PeriodMultiplier.k2X);
setRaw(m_centerPwm);
setZeroLatch();
LiveWindow.addActuator("Victor", getChannel(), this);
UsageReporting.report(tResourceType.kResourceType_Victor, getChannel());
}
/**
* Constructor.
*
* @param channel The PWM channel that the Victor is attached to. 0-9 are
* on-board, 10-19 are on the MXP port
*/
public Victor(final int channel) {
super(channel);
initVictor();
}
/**
* Set the PWM value.
*
* @deprecated For compatibility with CANJaguar
*
* The PWM value is set using a range of -1.0 to 1.0,
* appropriately scaling the value for the FPGA.
*
* @param speed The speed to set. Value should be between -1.0 and 1.0.
* @param syncGroup The update group to add this Set() to, pending
* UpdateSyncGroup(). If 0, update immediately.
*/
public void set(double speed, byte syncGroup) {
setSpeed(isInverted ? -speed : speed);
Feed();
}
/**
* Set the PWM value.
*
* The PWM value is set using a range of -1.0 to 1.0, appropriately scaling
* the value for the FPGA.
*
* @param speed The speed value between -1.0 and 1.0 to set.
*/
public void set(double speed) {
setSpeed(isInverted ? -speed : speed);
Feed();
}
/**
* Common interface for inverting direction of a speed controller
*
* @param isInverted The state of inversion true is inverted
*/
@Override
public void setInverted(boolean isInverted) {
this.isInverted = isInverted;
}
/**
* Common interface for the inverting direction of a speed controller.
*
* @return isInverted The state of inversion, true is inverted.
*
*/
@Override
public boolean getInverted() {
return this.isInverted;
}
/**
* Get the recently set value of the PWM.
*
* @return The most recently set value for the PWM between -1.0 and 1.0.
*/
public double get() {
return getSpeed();
}
/**
* Write out the PID value as seen in the PIDOutput base object.
*
* @param output Write out the PWM value as was found in the PIDController
*/
public void pidWrite(double output) {
set(output);
}
}

View File

@@ -0,0 +1,123 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType;
import edu.wpi.first.wpilibj.communication.UsageReporting;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
/**
* VEX Robotics Victor SP Speed Controller
*/
public class VictorSP extends SafePWM implements SpeedController {
private boolean isInverted = false;
/**
* Common initialization code called by all constructors.
*
* Note that the VictorSP uses the following bounds for PWM values. These
* values should work reasonably well for most controllers, but if users
* experience issues such as asymmetric behavior around the deadband or
* inability to saturate the controller in either direction, calibration is
* recommended. The calibration procedure can be found in the VictorSP User
* Manual available from CTRE.
*
* - 2.004ms = full "forward" - 1.52ms = the "high end" of the deadband range
* - 1.50ms = center of the deadband range (off) - 1.48ms = the "low end" of
* the deadband range - .997ms = full "reverse"
*/
protected void initVictorSP() {
setBounds(2.004, 1.52, 1.50, 1.48, .997);
setPeriodMultiplier(PeriodMultiplier.k1X);
setRaw(m_centerPwm);
setZeroLatch();
LiveWindow.addActuator("VictorSP", getChannel(), this);
UsageReporting.report(tResourceType.kResourceType_VictorSP, getChannel());
}
/**
* Constructor.
*
* @param channel The PWM channel that the VictorSP is attached to. 0-9 are
* on-board, 10-19 are on the MXP port
*/
public VictorSP(final int channel) {
super(channel);
initVictorSP();
}
/**
* Set the PWM value.
*
* @deprecated For compatibility with CANJaguar
*
* The PWM value is set using a range of -1.0 to 1.0,
* appropriately scaling the value for the FPGA.
*
* @param speed The speed to set. Value should be between -1.0 and 1.0.
* @param syncGroup The update group to add this Set() to, pending
* UpdateSyncGroup(). If 0, update immediately.
*/
public void set(double speed, byte syncGroup) {
setSpeed(isInverted ? -speed : speed);
Feed();
}
/**
* Set the PWM value.
*
* The PWM value is set using a range of -1.0 to 1.0, appropriately scaling
* the value for the FPGA.
*
* @param speed The speed value between -1.0 and 1.0 to set.
*/
public void set(double speed) {
setSpeed(isInverted ? -speed : speed);
Feed();
}
/**
* Common interface for inverting direction of a speed controller
*
* @param isInverted The state of inversion true is inverted
*/
@Override
public void setInverted(boolean isInverted) {
this.isInverted = isInverted;
}
/**
* Common interface for the inverting direction of a speed controller.
*
* @return isInverted The state of inversion, true is inverted.
*
*/
@Override
public boolean getInverted() {
return this.isInverted;
}
/**
* Get the recently set value of the PWM.
*
* @return The most recently set value for the PWM between -1.0 and 1.0.
*/
public double get() {
return getSpeed();
}
/**
* Write out the PID value as seen in the PIDOutput base object.
*
* @param output Write out the PWM value as was found in the PIDController
*/
public void pidWrite(double output) {
set(output);
}
}

View File

@@ -0,0 +1,42 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj.can;
import edu.wpi.first.wpilibj.communication.NIRioStatus;
import edu.wpi.first.wpilibj.util.UncleanStatusException;
public class CANExceptionFactory {
// FRC Error codes
static final int ERR_CANSessionMux_InvalidBuffer = -44086;
static final int ERR_CANSessionMux_MessageNotFound = -44087;
static final int ERR_CANSessionMux_NotAllowed = -44088;
static final int ERR_CANSessionMux_NotInitialized = -44089;
public static void checkStatus(int status, int messageID) throws CANInvalidBufferException,
CANMessageNotAllowedException, CANNotInitializedException, UncleanStatusException {
switch (status) {
case NIRioStatus.kRioStatusSuccess:
// Everything is ok... don't throw.
return;
case ERR_CANSessionMux_InvalidBuffer:
case NIRioStatus.kRIOStatusBufferInvalidSize:
throw new CANInvalidBufferException();
case ERR_CANSessionMux_MessageNotFound:
case NIRioStatus.kRIOStatusOperationTimedOut:
throw new CANMessageNotFoundException();
case ERR_CANSessionMux_NotAllowed:
case NIRioStatus.kRIOStatusFeatureNotSupported:
throw new CANMessageNotAllowedException("MessageID = " + Integer.toString(messageID));
case ERR_CANSessionMux_NotInitialized:
case NIRioStatus.kRIOStatusResourceNotInitialized:
throw new CANNotInitializedException();
default:
throw new UncleanStatusException("Fatal status code detected: " + Integer.toString(status));
}
}
}

View File

@@ -0,0 +1,19 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj.can;
/**
* Exception indicating that a CAN driver library entry-point was passed an
* invalid buffer. Typically, this is due to a buffer being too small to include
* the needed safety token.
*/
public class CANInvalidBufferException extends RuntimeException {
public CANInvalidBufferException() {
super();
}
}

View File

@@ -0,0 +1,504 @@
package edu.wpi.first.wpilibj.can;
// import com.ochafik.lang.jnaerator.runtime.LibraryExtractor;
// import com.ochafik.lang.jnaerator.runtime.MangledFunctionMapper;
// import com.sun.jna.Library;
// import com.sun.jna.Native;
// import com.sun.jna.NativeLibrary;
// import com.sun.jna.Pointer;
// import com.sun.jna.ptr.IntByReference;
import edu.wpi.first.wpilibj.hal.JNIWrapper;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
/**
* JNA Wrapper for library <b>CAN</b><br>
* This file was autogenerated by <a
* href="http://jnaerator.googlecode.com/">JNAerator</a>,<br>
* a tool written by <a href="http://ochafik.com/">Olivier Chafik</a> that <a
* href="http://code.google.com/p/jnaerator/wiki/CreditsAndLicense">uses a few
* opensource projects.</a>.<br>
* For help, please visit <a
* href="http://nativelibs4java.googlecode.com/">NativeLibs4Java</a> , <a
* href="http://rococoa.dev.java.net/">Rococoa</a>, or <a
* href="http://jna.dev.java.net/">JNA</a>.
*/
public class CANJNI extends JNIWrapper {
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_STATUS_LIMIT_REV = 0x02;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_CFG_MAX_VOUT = ((0x00020000 | 0x02000000 | 0x00001c00) | (7 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_PSTAT_CANERR_B0 = 30;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_SPD_DIS = ((0x00020000 | 0x02000000 | 0x00000400) | (1 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int CAN_MSGID_DTYPE_ACCEL = 0x05000000;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_STATUS_FAULT = ((0x00020000 | 0x02000000 | 0x00001400) | (7 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int CAN_MSGID_API_FIRMVER = 0x00000200;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_ICTRL_EN = ((0x00020000 | 0x02000000 | 0x00001000) | (0 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int CAN_MSGID_API_ENUMERATE = 0x00000240;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_SPD_EN = ((0x00020000 | 0x02000000 | 0x00000400) | (0 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_CFG_LIMIT_REV =
((0x00020000 | 0x02000000 | 0x00001c00) | (6 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_PSTAT_POS_B2 = 11;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_PSTAT_POS_B3 = 12;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_VCOMP_EN = ((0x00020000 | 0x02000000 | 0x00000800) | (0 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_PSTAT_POS_B0 = 9;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_PSTAT_POS_B1 = 10;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_HWVER = ((0x00020000 | 0x1f000000) | (5 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_STATUS_FAULT_ILIMIT = 0x01;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_ICTRL_DC = ((0x00020000 | 0x02000000 | 0x00001000) | (5 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_VOLT = (0x00020000 | 0x02000000 | 0x00000000);
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int CAN_API_MC_VCOMP = 0x00000800;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_PSTAT_END = 0;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_CFG_LIMIT_FWD =
((0x00020000 | 0x02000000 | 0x00001c00) | (5 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int CAN_MSGID_DTYPE_M = 0x1f000000;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int CAN_API_MC_ICTRL = 0x00001000;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int CAN_API_MC_CFG = 0x00001c00;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int CAN_MSGID_MFR_DEKA = 0x00030000;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int CAN_MSGID_API_SYSRST = 0x00000040;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_REF_QUAD_ENCODER = 0x03;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_SYNC_PEND_NOW = 0;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_STATUS_CMODE_CURRENT = 0x01;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_STATUS_TEMP = ((0x00020000 | 0x02000000 | 0x00001400) | (3 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_SPD_DC = ((0x00020000 | 0x02000000 | 0x00000400) | (5 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int CAN_API_MC_POS = 0x00000c00;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_STATUS_LIMIT_SFWD = 0x04;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_ICTRL_DIS = ((0x00020000 | 0x02000000 | 0x00001000) | (1 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_VOLT_SET = ((0x00020000 | 0x02000000 | 0x00000000) | (2 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int CAN_MSGID_API_HEARTBEAT = 0x00000140;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_FAULT_CURRENT = 0x01;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int CAN_MSGID_DTYPE_GYRO = 0x04000000;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_STATUS_FAULT_TLIMIT = 0x02;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int CAN_MSGID_MFR_S = 16;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_SPD_T_SET_NO_ACK =
((0x00020000 | 0x02000000 | 0x00000400) | (10 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int CAN_MSGID_MFR_M = 0x00ff0000;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_STATUS_CMODE_POS = 0x03;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_REF_POT = 0x01;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_HWVER_UNKNOWN = 0x00;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_CFG_BRAKE_COAST =
((0x00020000 | 0x02000000 | 0x00001c00) | (3 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_HWVER_JAG_1_0 = 0x01;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int CAN_MSGID_DEVNO_BCAST = 0x00000000;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_VOLT_T_SET = ((0x00020000 | 0x02000000 | 0x00000000) | (5 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_STATUS_LIMIT_STKY_SREV = 0x80;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_ICTRL_IC = ((0x00020000 | 0x02000000 | 0x00001000) | (4 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_FAULT_COMM = 0x10;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_ICTRL_T_SET_NO_ACK =
((0x00020000 | 0x02000000 | 0x00001000) | (9 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_PSTAT_SPD_B2 = 15;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_PSTAT_SPD_B1 = 14;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_PSTAT_STKY_FLT_CLR = 21;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_PSTAT_SPD_B3 = 16;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int CAN_STATUS_MFG_S = 16;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_SPD_SET_NO_ACK =
((0x00020000 | 0x02000000 | 0x00000400) | (11 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_STATUS_LIMIT = ((0x00020000 | 0x02000000 | 0x00001400) | (6 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_VOLT_EN = ((0x00020000 | 0x02000000 | 0x00000000) | (0 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_VOLT_RAMP_DIS = 0;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_PSTAT_TEMP_B0 = 7;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_PSTAT_TEMP_B1 = 8;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_POS_IC = ((0x00020000 | 0x02000000 | 0x00000c00) | (4 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int CAN_MSGID_DTYPE_MOTOR = 0x02000000;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_SPD_T_EN = ((0x00020000 | 0x02000000 | 0x00000400) | (7 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int CAN_MSGID_DEVNO_M = 0x0000003f;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_PSTAT_VOLTBUS_B1 = 4;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_UPD_PING = ((0x00020000 | 0x1f000000) | (0 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_POS_T_SET_NO_ACK =
((0x00020000 | 0x02000000 | 0x00000c00) | (10 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int CAN_MSGID_DEVNO_S = 0;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_TRUST_HEARTBEAT = ((0x00020000 | 0x1f000000) | (13 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_PSTAT_VOLTBUS_B0 = 3;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_PSTAT_SPD_B0 = 13;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_CFG = (0x00020000 | 0x02000000 | 0x00001c00);
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_PSTAT_FLT_COUNT_COMM = 28;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int CAN_MSGID_API_SYSHALT = 0x00000000;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_UPD_DOWNLOAD = ((0x00020000 | 0x1f000000) | (1 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_STATUS_CMODE = ((0x00020000 | 0x02000000 | 0x00001400) | (9 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_VCOMP_IN_RAMP =
((0x00020000 | 0x02000000 | 0x00000800) | (3 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_STATUS_FAULT_VLIMIT = 0x04;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_STATUS_LIMIT_SREV = 0x08;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int CAN_MSGID_DTYPE_S = 24;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_PSTAT_FLT_COUNT_VOLTBUS = 26;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int CAN_API_MC_STATUS = 0x00001400;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_VOLT_T_EN = ((0x00020000 | 0x02000000 | 0x00000000) | (4 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_STATUS_VOLTBUS =
((0x00020000 | 0x02000000 | 0x00001400) | (1 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_UPD = (0x00020000 | 0x1f000000);
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_UPD_REQUEST = ((0x00020000 | 0x1f000000) | (6 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int CAN_API_MC_VOLTAGE = 0x00000000;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_PSTAT_PER_EN_S3 =
((0x00020000 | 0x02000000 | 0x00001800) | (3 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_PSTAT_PER_EN_S2 =
((0x00020000 | 0x02000000 | 0x00001800) | (2 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int CAN_API_MC_PSTAT = 0x00001800;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_PSTAT_CANERR_B1 = 31;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_PSTAT_PER_EN_S1 =
((0x00020000 | 0x02000000 | 0x00001800) | (1 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_REF_ENCODER = 0x00;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_PSTAT_PER_EN_S0 =
((0x00020000 | 0x02000000 | 0x00001800) | (0 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_STATUS_CURRENT =
((0x00020000 | 0x02000000 | 0x00001400) | (2 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_POS_SET = ((0x00020000 | 0x02000000 | 0x00000c00) | (2 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_STATUS_LIMIT_STKY_FWD = 0x10;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_ICTRL = (0x00020000 | 0x02000000 | 0x00001000);
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_HWVER_JAG_2_0 = 0x02;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int CAN_STATUS_MFG_M = 0x00ff0000;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_PSTAT_LIMIT_CLR = 18;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_CFG_POT_TURNS =
((0x00020000 | 0x02000000 | 0x00001c00) | (2 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_POS_REF = ((0x00020000 | 0x02000000 | 0x00000c00) | (6 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_SPD_PC = ((0x00020000 | 0x02000000 | 0x00000400) | (3 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_STATUS_VOUT = ((0x00020000 | 0x02000000 | 0x00001400) | (10 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int CAN_MSGID_API_SYSRESUME = 0x00000280;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_UNTRUST_EN = ((0x00020000 | 0x1f000000) | (11 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_PSTAT_CANSTS = 29;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_POS_DC = ((0x00020000 | 0x02000000 | 0x00000c00) | (5 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_STATUS_POS = ((0x00020000 | 0x02000000 | 0x00001400) | (4 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_SPD_SET = ((0x00020000 | 0x02000000 | 0x00000400) | (2 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int CAN_MSGID_FULL_M = 0x1fffffff;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_STATUS_SPD = ((0x00020000 | 0x02000000 | 0x00001400) | (5 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_PSTAT_STKY_FLT_NCLR = 20;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_STATUS = (0x00020000 | 0x02000000 | 0x00001400);
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_TRUST_EN = ((0x00020000 | 0x1f000000) | (12 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_ICTRL_T_SET = ((0x00020000 | 0x02000000 | 0x00001000) | (7 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int CAN_STATUS_CODE_M = 0x0000ffff;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int CAN_STATUS_CODE_S = 0;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_POS_T_EN = ((0x00020000 | 0x02000000 | 0x00000c00) | (7 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_PSTAT = (0x00020000 | 0x02000000 | 0x00001800);
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_PSTAT_FAULT = 19;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_PSTAT_FLT_COUNT_GATE = 27;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_ICTRL_T_EN = ((0x00020000 | 0x02000000 | 0x00001000) | (6 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int CAN_MSGID_API_DEVQUERY = 0x000000c0;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int CAN_MSGID_DTYPE_USONIC = 0x06000000;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_STATUS_CMODE_VCOMP = 0x04;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_SPD_T_SET = ((0x00020000 | 0x02000000 | 0x00000400) | (8 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_POS_EN = ((0x00020000 | 0x02000000 | 0x00000c00) | (0 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_VOLT_DIS = ((0x00020000 | 0x02000000 | 0x00000000) | (1 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_STATUS_LIMIT_FWD = 0x01;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_VCOMP_DIS = ((0x00020000 | 0x02000000 | 0x00000800) | (1 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_REF_INV_ENCODER = 0x02;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_CFG_NUM_BRUSHES =
((0x00020000 | 0x02000000 | 0x00001c00) | (0 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int CAN_MSGID_DTYPE_RELAY = 0x03000000;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int CAN_MSGID_API_DEVASSIGN = 0x00000080;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_VOLT_T_SET_NO_ACK =
((0x00020000 | 0x02000000 | 0x00000000) | (7 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int CAN_API_MC_SPD = 0x00000400;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_CFG_ENC_LINES =
((0x00020000 | 0x02000000 | 0x00001c00) | (1 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_REF_NONE = 0xff;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_FAULT_VBUS = 0x04;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_VOLT_SET_RAMP =
((0x00020000 | 0x02000000 | 0x00000000) | (3 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_SPD_REF = ((0x00020000 | 0x02000000 | 0x00000400) | (6 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_STATUS_POWER = ((0x00020000 | 0x02000000 | 0x00001400) | (8 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_PSTAT_VOLTOUT_B1 = 2;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_VCOMP_SET_NO_ACK =
((0x00020000 | 0x02000000 | 0x00000800) | (9 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_PSTAT_VOLTOUT_B0 = 1;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_CFG_LIMIT_MODE =
((0x00020000 | 0x02000000 | 0x00001c00) | (4 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_PSTAT_VOUT_B1 = 23;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_UPD_SEND_DATA = ((0x00020000 | 0x1f000000) | (2 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_PSTAT_FLT_COUNT_CURRENT = 24;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_PSTAT_VOUT_B0 = 22;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_PSTAT_CFG_S0 = ((0x00020000 | 0x02000000 | 0x00001800) | (4 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_PSTAT_LIMIT_NCLR = 17;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_PSTAT_CFG_S1 = ((0x00020000 | 0x02000000 | 0x00001800) | (5 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_PSTAT_CFG_S2 = ((0x00020000 | 0x02000000 | 0x00001800) | (6 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_PSTAT_CFG_S3 = ((0x00020000 | 0x02000000 | 0x00001800) | (7 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_VCOMP_SET = ((0x00020000 | 0x02000000 | 0x00000800) | (2 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int CAN_MSGID_API_UPDATE = 0x000001c0;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_CFG_FAULT_TIME =
((0x00020000 | 0x02000000 | 0x00001c00) | (8 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_STATUS_VOLTOUT =
((0x00020000 | 0x02000000 | 0x00001400) | (0 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_ICTRL_SET = ((0x00020000 | 0x02000000 | 0x00001000) | (2 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int CAN_MSGID_API_M = 0x0000ffc0;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_STATUS_CMODE_SPEED = 0x02;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int CAN_MSGID_API_CLASS_M = 0x0000fc00;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_PSTAT_DATA_S3 =
((0x00020000 | 0x02000000 | 0x00001800) | (11 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int CAN_MSGID_API_S = 6;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_STATUS_FLT_COUNT =
((0x00020000 | 0x02000000 | 0x00001400) | (12 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_PSTAT_DATA_S2 =
((0x00020000 | 0x02000000 | 0x00001800) | (10 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_PSTAT_DATA_S1 =
((0x00020000 | 0x02000000 | 0x00001800) | (9 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_PSTAT_DATA_S0 =
((0x00020000 | 0x02000000 | 0x00001800) | (8 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_ICTRL_PC = ((0x00020000 | 0x02000000 | 0x00001000) | (3 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_POS_PC = ((0x00020000 | 0x02000000 | 0x00000c00) | (3 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int CAN_MSGID_MFR_LM = 0x00020000;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_POS_DIS = ((0x00020000 | 0x02000000 | 0x00000c00) | (1 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int CAN_MSGID_DTYPE_BCAST = 0x00000000;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_STATUS_CMODE_VOLT = 0x00;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int CAN_STATUS_DTYPE_S = 24;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_POS_SET_NO_ACK =
((0x00020000 | 0x02000000 | 0x00000c00) | (11 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_FAULT_GATE_DRIVE = 0x08;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int CAN_STATUS_DTYPE_M = 0x1f000000;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_STATUS_LIMIT_STKY_REV = 0x20;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int CAN_MSGID_DTYPE_ROBOT = 0x01000000;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int CAN_API_MC_ACK = 0x00002000;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_VCOMP = (0x00020000 | 0x02000000 | 0x00000800);
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_UPD_ACK = ((0x00020000 | 0x1f000000) | (4 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_VCOMP_COMP_RAMP =
((0x00020000 | 0x02000000 | 0x00000800) | (4 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_VCOMP_T_SET_NO_ACK =
((0x00020000 | 0x02000000 | 0x00000800) | (8 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_POS = (0x00020000 | 0x02000000 | 0x00000c00);
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int CAN_MSGID_API_SYNC = 0x00000180;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_ICTRL_SET_NO_ACK =
((0x00020000 | 0x02000000 | 0x00001000) | (10 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_PSTAT_CURRENT_B1 = 6;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_SPD = (0x00020000 | 0x02000000 | 0x00000400);
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_PSTAT_CURRENT_B0 = 5;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int CAN_MSGID_DTYPE_UPDATE = 0x1f000000;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_SPD_IC = ((0x00020000 | 0x02000000 | 0x00000400) | (4 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_ACK = (0x00020000 | 0x02000000 | 0x00002000);
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_FAULT_TEMP = 0x02;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_VCOMP_T_SET = ((0x00020000 | 0x02000000 | 0x00000800) | (6 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_PSTAT_FLT_COUNT_TEMP = 25;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_VOLT_SET_NO_ACK =
((0x00020000 | 0x02000000 | 0x00000000) | (8 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int CAN_MSGID_DTYPE_GEART = 0x07000000;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int CAN_MSGID_MFR_NI = 0x00010000;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_POS_T_SET = ((0x00020000 | 0x02000000 | 0x00000c00) | (8 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_STATUS_STKY_FLT =
((0x00020000 | 0x02000000 | 0x00001400) | (11 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_UPD_RESET = ((0x00020000 | 0x1f000000) | (3 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int CAN_MSGID_API_ID_M = 0x000003c0;
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_API_VCOMP_T_EN = ((0x00020000 | 0x02000000 | 0x00000800) | (5 << 6));
/** <i>native declaration : src\main\include\CAN\can_proto.h</i> */
public static final int LM_STATUS_LIMIT_STKY_SFWD = 0x40;
public static final int CAN_SEND_PERIOD_NO_REPEAT = 0;
public static final int CAN_SEND_PERIOD_STOP_REPEATING = -1;
/* Flags in the upper bits of the messageID */
public static final int CAN_IS_FRAME_REMOTE = 0x80000000;
public static final int CAN_IS_FRAME_11BIT = 0x40000000;
public static native void FRCNetworkCommunicationCANSessionMuxSendMessage(int messageID,
ByteBuffer data, int periodMs);
public static native ByteBuffer FRCNetworkCommunicationCANSessionMuxReceiveMessage(
IntBuffer messageID, int messageIDMask, ByteBuffer timeStamp);
}

View File

@@ -0,0 +1,43 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj.can;
/**
* Exception indicating that the CAN driver layer has not been initialized. This
* happens when an entry-point is called before a CAN driver plugin has been
* installed.
*/
public class CANJaguarVersionException extends RuntimeException {
public static final int kMinLegalFIRSTFirmwareVersion = 101;
// 3330 was the first shipping RDK firmware version for the Jaguar
public static final int kMinRDKFirmwareVersion = 3330;
public CANJaguarVersionException(int deviceNumber, int fwVersion) {
super(getString(deviceNumber, fwVersion));
System.out.println("fwVersion[" + deviceNumber + "]: " + fwVersion);
}
static String getString(int deviceNumber, int fwVersion) {
String msg;
if (fwVersion < kMinRDKFirmwareVersion) {
msg =
"Jaguar " + deviceNumber
+ " firmware is too old. It must be updated to at least version "
+ Integer.toString(kMinLegalFIRSTFirmwareVersion)
+ " of the FIRST approved firmware!";
} else {
msg =
"Jaguar " + deviceNumber
+ " firmware is not FIRST approved. It must be updated to at least version "
+ Integer.toString(kMinLegalFIRSTFirmwareVersion)
+ " of the FIRST approved firmware!";
}
return msg;
}
}

View File

@@ -0,0 +1,18 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj.can;
/**
* Exception indicating that the Jaguar CAN Driver layer refused to send a
* restricted message ID to the CAN bus.
*/
public class CANMessageNotAllowedException extends RuntimeException {
public CANMessageNotAllowedException(String msg) {
super(msg);
}
}

View File

@@ -0,0 +1,19 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj.can;
/**
* Exception indicating that a can message is not available from Network
* Communications. This usually just means we already have the most recent value
* cached locally.
*/
public class CANMessageNotFoundException extends RuntimeException {
public CANMessageNotFoundException() {
super();
}
}

View File

@@ -0,0 +1,19 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj.can;
/**
* Exception indicating that the CAN driver layer has not been initialized. This
* happens when an entry-point is called before a CAN driver plugin has been
* installed.
*/
public class CANNotInitializedException extends RuntimeException {
public CANNotInitializedException() {
super();
}
}

View File

@@ -0,0 +1,979 @@
package edu.wpi.first.wpilibj.communication;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.nio.ShortBuffer;
import edu.wpi.first.wpilibj.hal.JNIWrapper;
/**
* JNA Wrapper for library <b>FRC_NetworkCommunications</b><br>
* This file was autogenerated by <a
* href="http://jnaerator.googlecode.com/">JNAerator</a>,<br>
* a tool written by <a href="http://ochafik.com/">Olivier Chafik</a> that <a
* href="http://code.google.com/p/jnaerator/wiki/CreditsAndLicense">uses a few
* opensource projects.</a>.<br>
* For help, please visit <a
* href="http://nativelibs4java.googlecode.com/">NativeLibs4Java</a> , <a
* href="http://rococoa.dev.java.net/">Rococoa</a>, or <a
* href="http://jna.dev.java.net/">JNA</a>.
*/
public class FRCNetworkCommunicationsLibrary extends JNIWrapper {
// public static final String JNA_LIBRARY_NAME =
// LibraryExtractor.getLibraryPath("FRC_NetworkCommunications", true,
// FRC_NetworkCommunicationsLibrary.class);
// public static final NativeLibrary JNA_NATIVE_LIB =
// NativeLibrary.getInstance(FRC_NetworkCommunicationsLibrary.JNA_LIBRARY_NAME,
// MangledFunctionMapper.DEFAULT_OPTIONS);
// static {
// System.loadLibrary("JNIWrappers");
// Native.register(FRC_NetworkCommunicationsLibrary.class,
// FRC_NetworkCommunicationsLibrary.JNA_NATIVE_LIB);
// }
/**
* <i>native declaration : src\main\include\NetworkCommunication\LoadOut.h</i><br>
* enum values
*/
public static interface tModuleType {
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\LoadOut.h:9</i>
*/
public static final int kModuleType_Unknown = 0x00;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\LoadOut.h:10</i>
*/
public static final int kModuleType_Analog = 0x01;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\LoadOut.h:11</i>
*/
public static final int kModuleType_Digital = 0x02;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\LoadOut.h:12</i>
*/
public static final int kModuleType_Solenoid = 0x03;
};
/**
* <i>native declaration : src\main\include\NetworkCommunication\LoadOut.h</i><br>
* enum values
*/
public static interface tTargetClass {
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\LoadOut.h:16</i>
*/
public static final int kTargetClass_Unknown = 0x00;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\LoadOut.h:17</i>
*/
public static final int kTargetClass_FRC1 = 0x10;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\LoadOut.h:18</i>
*/
public static final int kTargetClass_FRC2 = 0x20;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\LoadOut.h:19</i>
*/
public static final int kTargetClass_FRC2_Analog =
(int) FRCNetworkCommunicationsLibrary.tTargetClass.kTargetClass_FRC2
| (int) FRCNetworkCommunicationsLibrary.tModuleType.kModuleType_Analog;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\LoadOut.h:20</i>
*/
public static final int kTargetClass_FRC2_Digital =
(int) FRCNetworkCommunicationsLibrary.tTargetClass.kTargetClass_FRC2
| (int) FRCNetworkCommunicationsLibrary.tModuleType.kModuleType_Digital;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\LoadOut.h:21</i>
*/
public static final int kTargetClass_FRC2_Solenoid =
(int) FRCNetworkCommunicationsLibrary.tTargetClass.kTargetClass_FRC2
| (int) FRCNetworkCommunicationsLibrary.tModuleType.kModuleType_Solenoid;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\LoadOut.h:22</i>
*/
public static final int kTargetClass_FamilyMask = 0xF0;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\LoadOut.h:23</i>
*/
public static final int kTargetClass_ModuleMask = 0x0F;
};
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h</i><br>
* enum values
*/
public static interface tResourceType {
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:10</i>
*/
public static final int kResourceType_Controller = 0;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:11</i>
*/
public static final int kResourceType_Module = 1;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:12</i>
*/
public static final int kResourceType_Language = 2;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:13</i>
*/
public static final int kResourceType_CANPlugin = 3;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:14</i>
*/
public static final int kResourceType_Accelerometer = 4;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:15</i>
*/
public static final int kResourceType_ADXL345 = 5;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:16</i>
*/
public static final int kResourceType_AnalogChannel = 6;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:17</i>
*/
public static final int kResourceType_AnalogTrigger = 7;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:18</i>
*/
public static final int kResourceType_AnalogTriggerOutput = 8;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:19</i>
*/
public static final int kResourceType_CANJaguar = 9;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:20</i>
*/
public static final int kResourceType_Compressor = 10;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:21</i>
*/
public static final int kResourceType_Counter = 11;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:22</i>
*/
public static final int kResourceType_Dashboard = 12;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:23</i>
*/
public static final int kResourceType_DigitalInput = 13;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:24</i>
*/
public static final int kResourceType_DigitalOutput = 14;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:25</i>
*/
public static final int kResourceType_DriverStationCIO = 15;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:26</i>
*/
public static final int kResourceType_DriverStationEIO = 16;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:27</i>
*/
public static final int kResourceType_DriverStationLCD = 17;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:28</i>
*/
public static final int kResourceType_Encoder = 18;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:29</i>
*/
public static final int kResourceType_GearTooth = 19;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:30</i>
*/
public static final int kResourceType_Gyro = 20;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:31</i>
*/
public static final int kResourceType_I2C = 21;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:32</i>
*/
public static final int kResourceType_Framework = 22;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:33</i>
*/
public static final int kResourceType_Jaguar = 23;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:34</i>
*/
public static final int kResourceType_Joystick = 24;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:35</i>
*/
public static final int kResourceType_Kinect = 25;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:36</i>
*/
public static final int kResourceType_KinectStick = 26;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:37</i>
*/
public static final int kResourceType_PIDController = 27;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:38</i>
*/
public static final int kResourceType_Preferences = 28;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:39</i>
*/
public static final int kResourceType_PWM = 29;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:40</i>
*/
public static final int kResourceType_Relay = 30;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:41</i>
*/
public static final int kResourceType_RobotDrive = 31;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:42</i>
*/
public static final int kResourceType_SerialPort = 32;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:43</i>
*/
public static final int kResourceType_Servo = 33;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:44</i>
*/
public static final int kResourceType_Solenoid = 34;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:45</i>
*/
public static final int kResourceType_SPI = 35;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:46</i>
*/
public static final int kResourceType_Task = 36;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:47</i>
*/
public static final int kResourceType_Ultrasonic = 37;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:48</i>
*/
public static final int kResourceType_Victor = 38;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:49</i>
*/
public static final int kResourceType_Button = 39;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:50</i>
*/
public static final int kResourceType_Command = 40;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:51</i>
*/
public static final int kResourceType_AxisCamera = 41;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:52</i>
*/
public static final int kResourceType_PCVideoServer = 42;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:53</i>
*/
public static final int kResourceType_SmartDashboard = 43;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:54</i>
*/
public static final int kResourceType_Talon = 44;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:55</i>
*/
public static final int kResourceType_HiTechnicColorSensor = 45;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:56</i>
*/
public static final int kResourceType_HiTechnicAccel = 46;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:57</i>
*/
public static final int kResourceType_HiTechnicCompass = 47;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:58</i>
*/
public static final int kResourceType_SRF08 = 48;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:59</i>
*/
public static final int kResourceType_AnalogOutput = 49;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:60</i>
*/
public static final int kResourceType_VictorSP = 50;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:61</i>
*/
public static final int kResourceType_TalonSRX = 51;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:62</i>
*/
public static final int kResourceType_CANTalonSRX = 52;
};
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h</i><br>
* enum values
*/
public static interface tInstances {
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:63</i>
*/
public static final int kLanguage_LabVIEW = 1;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:64</i>
*/
public static final int kLanguage_CPlusPlus = 2;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:65</i>
*/
public static final int kLanguage_Java = 3;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:66</i>
*/
public static final int kLanguage_Python = 4;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:68</i>
*/
public static final int kCANPlugin_BlackJagBridge = 1;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:69</i>
*/
public static final int kCANPlugin_2CAN = 2;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:71</i>
*/
public static final int kFramework_Iterative = 1;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:72</i>
*/
public static final int kFramework_Sample = 2;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:74</i>
*/
public static final int kRobotDrive_ArcadeStandard = 1;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:75</i>
*/
public static final int kRobotDrive_ArcadeButtonSpin = 2;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:76</i>
*/
public static final int kRobotDrive_ArcadeRatioCurve = 3;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:77</i>
*/
public static final int kRobotDrive_Tank = 4;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:78</i>
*/
public static final int kRobotDrive_MecanumPolar = 5;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:79</i>
*/
public static final int kRobotDrive_MecanumCartesian = 6;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:81</i>
*/
public static final int kDriverStationCIO_Analog = 1;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:82</i>
*/
public static final int kDriverStationCIO_DigitalIn = 2;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:83</i>
*/
public static final int kDriverStationCIO_DigitalOut = 3;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:85</i>
*/
public static final int kDriverStationEIO_Acceleration = 1;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:86</i>
*/
public static final int kDriverStationEIO_AnalogIn = 2;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:87</i>
*/
public static final int kDriverStationEIO_AnalogOut = 3;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:88</i>
*/
public static final int kDriverStationEIO_Button = 4;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:89</i>
*/
public static final int kDriverStationEIO_LED = 5;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:90</i>
*/
public static final int kDriverStationEIO_DigitalIn = 6;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:91</i>
*/
public static final int kDriverStationEIO_DigitalOut = 7;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:92</i>
*/
public static final int kDriverStationEIO_FixedDigitalOut = 8;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:93</i>
*/
public static final int kDriverStationEIO_PWM = 9;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:94</i>
*/
public static final int kDriverStationEIO_Encoder = 10;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:95</i>
*/
public static final int kDriverStationEIO_TouchSlider = 11;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:97</i>
*/
public static final int kADXL345_SPI = 1;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:98</i>
*/
public static final int kADXL345_I2C = 2;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:100</i>
*/
public static final int kCommand_Scheduler = 1;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:102</i>
*/
public static final int kSmartDashboard_Instance = 1;
};
/**
* <i>native declaration : src\main\include\NetworkCommunication\FRCComm.h</i>
*/
public static final int kFRC_NetworkCommunication_DynamicType_DSEnhancedIO_Input = 17;
/**
* <i>native declaration : src\main\include\NetworkCommunication\FRCComm.h</i>
*/
public static final int kFRC_NetworkCommunication_DynamicType_Kinect_Vertices1 = 21;
/**
* <i>native declaration : src\main\include\NetworkCommunication\FRCComm.h</i>
*/
public static final int SYS_STATUS_DATA_SIZE = 44;
/**
* <i>native declaration : src\main\include\NetworkCommunication\FRCComm.h</i>
*/
public static final int kFRC_NetworkCommunication_DynamicType_Kinect_Custom = 25;
/**
* <i>native declaration : src\main\include\NetworkCommunication\FRCComm.h</i>
*/
public static final int kFRC_NetworkCommunication_DynamicType_Kinect_Vertices2 = 23;
/**
* <i>native declaration : src\main\include\NetworkCommunication\FRCComm.h</i>
*/
public static final int kFRC_NetworkCommunication_DynamicType_Kinect_Header = 19;
/**
* <i>native declaration : src\main\include\NetworkCommunication\FRCComm.h</i>
*/
public static final int kFRC_NetworkCommunication_DynamicType_Kinect_Joystick = 24;
/**
* <i>native declaration : src\main\include\NetworkCommunication\FRCComm.h</i>
*/
public static final int IO_CONFIG_DATA_SIZE = 32;
/**
* <i>native declaration : src\main\include\NetworkCommunication\LoadOut.h</i>
*/
public static final int kMaxModuleNumber = 2;
/**
* <i>native declaration : src\main\include\NetworkCommunication\FRCComm.h</i>
*/
public static final int kFRC_NetworkCommunication_DynamicType_DSEnhancedIO_Output = 18;
/**
* <i>native declaration : src\main\include\NetworkCommunication\FRCComm.h</i>
*/
public static final int kFRC_NetworkCommunication_DynamicType_Kinect_Extra2 = 22;
/**
* <i>native declaration : src\main\include\NetworkCommunication\FRCComm.h</i>
*/
public static final int kFRC_NetworkCommunication_DynamicType_Kinect_Extra1 = 20;
/**
* <i>native declaration : src\main\include\NetworkCommunication\FRCComm.h</i>
*/
public static final int USER_DS_LCD_DATA_SIZE = 128;
/**
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h</i>
*/
public static final int kUsageReporting_version = 1;
/**
* <i>native declaration : src\main\include\NetworkCommunication\FRCComm.h</i>
*/
public static final int USER_STATUS_DATA_SIZE = (984 - 32 - 44);
/**
* Original signature :
* <code>uint32_t FRC_NetworkCommunication_nAICalibration_getLSBWeight(const uint32_t, const uint32_t, int32_t*)</code>
* <br>
* <i>native declaration :
* src\main\include\NetworkCommunication\AICalibration.h:7</i><br>
*$
* @deprecated use the safer methods
* {@link #FRC_NetworkCommunication_nAICalibration_getLSBWeight(int, int, java.nio.IntBuffer)}
* and
* {@link #FRC_NetworkCommunication_nAICalibration_getLSBWeight(int, int, com.sun.jna.ptr.IntByReference)}
* instead
*/
// @Deprecated
// public static native int
// FRC_NetworkCommunication_nAICalibration_getLSBWeight(int aiSystemIndex, int
// channel, Integer status);
/**
* Original signature :
* <code>uint32_t FRC_NetworkCommunication_nAICalibration_getLSBWeight(const uint32_t, const uint32_t, int32_t*)</code>
* <br>
* <i>native declaration :
* src\main\include\NetworkCommunication\AICalibration.h:7</i>
*/
public static native int FRCNetworkCommunicationAICalibrationGetLSBWeight(int aiSystemIndex,
int channel, Integer status);
/**
* Original signature :
* <code>int32_t FRC_NetworkCommunication_nAICalibration_getOffset(const uint32_t, const uint32_t, int32_t*)</code>
* <br>
* <i>native declaration :
* src\main\include\NetworkCommunication\AICalibration.h:8</i><br>
*$
* @deprecated use the safer methods
* {@link #FRC_NetworkCommunication_nAICalibration_getOffset(int, int, java.nio.IntBuffer)}
* and
* {@link #FRC_NetworkCommunication_nAICalibration_getOffset(int, int, com.sun.jna.ptr.IntByReference)}
* instead
*/
// @Deprecated
// public static native int
// FRC_NetworkCommunication_nAICalibration_getOffset(int aiSystemIndex, int
// channel, Integer status);
/**
* Original signature :
* <code>int32_t FRC_NetworkCommunication_nAICalibration_getOffset(const uint32_t, const uint32_t, int32_t*)</code>
* <br>
* <i>native declaration :
* src\main\include\NetworkCommunication\AICalibration.h:8</i>
*/
public static native int FRCNetworkCommunicationAICalibrationGetOffset(int aiSystemIndex,
int channel, Integer status);
/**
* Original signature : <code>tTargetClass getTargetClass()</code><br>
* <i>native declaration :
* src\main\include\NetworkCommunication\LoadOut.h:25</i>
*/
public static native int getTargetClass();
/**
* Original signature :
* <code>uint32_t FRC_NetworkCommunication_nLoadOut_getModulePresence(uint32_t, uint8_t)</code>
* <br>
* <i>native declaration :
* src\main\include\NetworkCommunication\LoadOut.h:32</i>
*/
public static native int FRCNetworkCommunicationLoadOutGetModulePresence(int moduleType,
byte moduleNumber);
/**
* Original signature :
* <code>uint32_t FRC_NetworkCommunication_nLoadOut_getTargetClass()</code><br>
* <i>native declaration :
* src\main\include\NetworkCommunication\LoadOut.h:33</i>
*/
public static native int FRCNetworkCommunicationLoadOutGetTargetClass();
/**
* Original signature :
* <code>STATUS moduleNameFindBySymbolName(const char*, char*)</code><br>
*$
* @param symbol symbol name to look for<br>
* @param module where to return module name<br>
* <i>native declaration :
* src\main\include\NetworkCommunication\symModuleLink.h:6</i><br>
* @deprecated use the safer methods
* {@link #moduleNameFindBySymbolName(java.lang.String, java.nio.ByteBuffer)}
* and
* {@link #moduleNameFindBySymbolName(com.sun.jna.Pointer, com.sun.jna.Pointer)}
* instead
*/
// @Deprecated
// public static native FRC_NetworkCommunicationsLibrary.STATUS
// moduleNameFindBySymbolName(Pointer symbol, Pointer module);
/**
* Original signature :
* <code>STATUS moduleNameFindBySymbolName(const char*, char*)</code><br>
*$
* @param symbol symbol name to look for<br>
* @param module where to return module name<br>
* <i>native declaration :
* src\main\include\NetworkCommunication\symModuleLink.h:6</i>
*/
// public static native FRC_NetworkCommunicationsLibrary.STATUS
// moduleNameFindBySymbolName(String symbol, ByteBuffer module);
/**
* Report the usage of a resource of interest. <br>
*
* <br>
*$
* @param resource one of the values in the tResourceType above (max value
* 51). <br>
* @param instanceNumber an index that identifies the resource instance. <br>
* @param context an optional additional context number for some cases (such
* as module number). Set to 0 to omit. <br>
* @param feature a string to be included describing features in use on a
* specific resource. Setting the same resource more than once allows
* you to change the feature string.<br>
* Original signature :
* <code>uint32_t report(tResourceType, uint8_t, uint8_t, const char*)</code>
* <br>
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:113</i><br>
* @deprecated use the safer methods
* {@link #report(int, byte, byte, java.lang.String)} and
* {@link #report(int, byte, byte, com.sun.jna.Pointer)} instead
*/
// @Deprecated
// public static native int report(int resource, byte instanceNumber, byte
// context, Pointer feature);
/**
* Report the usage of a resource of interest. <br>
*
* <br>
*$
* @param resource one of the values in the tResourceType above (max value
* 51). <br>
* @param instanceNumber an index that identifies the resource instance. <br>
* @param context an optional additional context number for some cases (such
* as module number). Set to 0 to omit. <br>
* @param feature a string to be included describing features in use on a
* specific resource. Setting the same resource more than once allows
* you to change the feature string.<br>
* Original signature :
* <code>uint32_t report(tResourceType, uint8_t, uint8_t, const char*)</code>
* <br>
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:113</i>
*/
public static native int report(int resource, byte instanceNumber, byte context, String feature);
/**
* Original signature :
* <code>uint32_t FRC_NetworkCommunication_nUsageReporting_report(uint8_t, uint8_t, uint8_t, const char*)</code>
* <br>
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:120</i><br>
*$
* @deprecated use the safer methods
* {@link #FRC_NetworkCommunication_nUsageReporting_report(byte, byte, byte, java.lang.String)}
* and
* {@link #FRC_NetworkCommunication_nUsageReporting_report(byte, byte, byte, com.sun.jna.Pointer)}
* instead
*/
// @Deprecated
// public static native int
// FRC_NetworkCommunication_nUsageReporting_report(byte resource, byte
// instanceNumber, byte context, Pointer feature);
/**
* Original signature :
* <code>uint32_t FRC_NetworkCommunication_nUsageReporting_report(uint8_t, uint8_t, uint8_t, const char*)</code>
* <br>
* <i>native declaration :
* src\main\include\NetworkCommunication\UsageReporting.h:120</i>
*/
public static native int FRCNetworkCommunicationUsageReportingReport(byte resource,
byte instanceNumber, byte context, String feature);
/**
* Original signature :
* <code>void getFPGAHardwareVersion(uint16_t*, uint32_t*)</code><br>
* <i>native declaration :
* src\main\include\NetworkCommunication\FRCComm.h:124</i><br>
*$
* @deprecated use the safer methods
* {@link #getFPGAHardwareVersion(java.nio.ShortBuffer, java.nio.IntBuffer)}
* and
* {@link #getFPGAHardwareVersion(com.sun.jna.ptr.ShortByReference, com.sun.jna.ptr.IntByReference)}
* instead
*/
// @Deprecated
// public static native void getFPGAHardwareVersion(ShortByReference
// fpgaVersion, IntByReference fpgaRevision);
/**
* Original signature :
* <code>void getFPGAHardwareVersion(uint16_t*, uint32_t*)</code><br>
* <i>native declaration :
* src\main\include\NetworkCommunication\FRCComm.h:124</i>
*/
public static native void getFPGAHardwareVersion(ShortBuffer fpgaVersion, IntBuffer fpgaRevision);
/**
* Original signature : <code>int setErrorData(const char*, int, int)</code><br>
* <i>native declaration :
* src\main\include\NetworkCommunication\FRCComm.h:136</i><br>
*$
* @deprecated use the safer methods
* {@link #setErrorData(java.lang.String, int, int)} and
* {@link #setErrorData(com.sun.jna.Pointer, int, int)} instead
*/
// @Deprecated
// public static native int setErrorData(Pointer errors, int errorsLength, int
// wait_ms);
/**
* Original signature : <code>int setErrorData(const char*, int, int)</code><br>
* <i>native declaration :
* src\main\include\NetworkCommunication\FRCComm.h:136</i>
*/
public static native int setErrorData(String errors, int errorsLength, int wait_ms);
/**
* Original signature : <code>int overrideIOConfig(const char*, int)</code><br>
* <i>native declaration :
* src\main\include\NetworkCommunication\FRCComm.h:138</i><br>
*$
* @deprecated use the safer methods
* {@link #overrideIOConfig(java.lang.String, int)} and
* {@link #overrideIOConfig(com.sun.jna.Pointer, int)} instead
*/
// @Deprecated
// public static native int overrideIOConfig(String ioConfig, int wait_ms);
/**
* Original signature : <code>int overrideIOConfig(const char*, int)</code><br>
* <i>native declaration :
* src\main\include\NetworkCommunication\FRCComm.h:138</i>
*/
public static native int overrideIOConfig(String ioConfig, int wait_ms);
/**
* Original signature : <code>void setNewDataSem(pthread_mutex_t*)</code><br>
* <i>native declaration :
* src\main\include\NetworkCommunication\FRCComm.h:147</i>
*/
public static native void setNewDataSem(long mutexId);
/**
* Original signature : <code>void setResyncSem(pthread_mutex_t*)</code><br>
* <i>native declaration :
* src\main\include\NetworkCommunication\FRCComm.h:148</i>
*/
// public static native void
// setResyncSem(FRC_NetworkCommunicationsLibrary.pthread_mutex_t
// pthread_mutex_tPtr1);
/**
* Original signature : <code>void signalResyncActionDone()</code><br>
* <i>native declaration :
* src\main\include\NetworkCommunication\FRCComm.h:150</i>
*/
public static native void signalResyncActionDone();
/**
* this uint32_t is really a LVRefNum<br>
* Original signature : <code>void setNewDataOccurRef(uint32_t)</code><br>
* <i>native declaration :
* src\main\include\NetworkCommunication\FRCComm.h:154</i>
*/
public static native void setNewDataOccurRef(int refnum);
/**
* Original signature : <code>void setResyncOccurRef(uint32_t)</code><br>
* <i>native declaration :
* src\main\include\NetworkCommunication\FRCComm.h:156</i>
*/
public static native void setResyncOccurRef(int refnum);
/**
* Original signature :
* <code>void FRC_NetworkCommunication_getVersionString(char*)</code><br>
* <i>native declaration :
* src\main\include\NetworkCommunication\FRCComm.h:159</i><br>
*$
* @deprecated use the safer methods
* {@link #FRC_NetworkCommunication_getVersionString(java.nio.ByteBuffer)}
* and
* {@link #FRC_NetworkCommunication_getVersionString(com.sun.jna.Pointer)}
* instead
*/
// @Deprecated
// public static native void FRC_NetworkCommunication_getVersionString(Pointer
// version);
/**
* Original signature :
* <code>void FRC_NetworkCommunication_getVersionString(char*)</code><br>
* <i>native declaration :
* src\main\include\NetworkCommunication\FRCComm.h:159</i>
*/
public static native void FRCNetworkCommunicationGetVersionString(ByteBuffer version);
public static native void FRCNetworkCommunicationObserveUserProgramStarting();
public static native void FRCNetworkCommunicationObserveUserProgramDisabled();
public static native void FRCNetworkCommunicationObserveUserProgramAutonomous();
public static native void FRCNetworkCommunicationObserveUserProgramTeleop();
public static native void FRCNetworkCommunicationObserveUserProgramTest();
public static native void FRCNetworkCommunicationReserve();
private static native int NativeHALGetControlWord();
public static HALControlWord HALGetControlWord() {
int word = NativeHALGetControlWord();
return new HALControlWord((word & 1) != 0, ((word >> 1) & 1) != 0, ((word >> 2) & 1) != 0,
((word >> 3) & 1) != 0, ((word >> 4) & 1) != 0, ((word >> 5) & 1) != 0);
}
private static native int NativeHALGetAllianceStation();
public static HALAllianceStationID HALGetAllianceStation() {
switch (NativeHALGetAllianceStation()) {
case 0:
return HALAllianceStationID.Red1;
case 1:
return HALAllianceStationID.Red2;
case 2:
return HALAllianceStationID.Red3;
case 3:
return HALAllianceStationID.Blue1;
case 4:
return HALAllianceStationID.Blue2;
case 5:
return HALAllianceStationID.Blue3;
default:
return null;
}
}
public static int kMaxJoystickAxes = 12;
public static int kMaxJoystickPOVs = 12;
public static native short[] HALGetJoystickAxes(byte joystickNum);
public static native short[] HALGetJoystickPOVs(byte joystickNum);
public static native int HALGetJoystickButtons(byte joystickNum, ByteBuffer count);
public static native int HALSetJoystickOutputs(byte joystickNum, int outputs, short leftRumble,
short rightRumble);
public static native int HALGetJoystickIsXbox(byte joystickNum);
public static native int HALGetJoystickType(byte joystickNum);
public static native String HALGetJoystickName(byte joystickNum);
public static native float HALGetMatchTime();
public static native boolean HALGetSystemActive();
public static native boolean HALGetBrownedOut();
public static native int HALSetErrorData(String error);
}

View File

@@ -0,0 +1,5 @@
package edu.wpi.first.wpilibj.communication;
public enum HALAllianceStationID {
Red1, Red2, Red3, Blue1, Blue2, Blue3
}

View File

@@ -0,0 +1,49 @@
package edu.wpi.first.wpilibj.communication;
/**
* A wrapper for the HALControlWord bitfield
*/
public class HALControlWord {
private boolean m_enabled;
private boolean m_autonomous;
private boolean m_test;
private boolean m_eStop;
private boolean m_fmsAttached;
private boolean m_dsAttached;
protected HALControlWord(boolean enabled, boolean autonomous, boolean test, boolean eStop,
boolean fmsAttached, boolean dsAttached) {
m_enabled = enabled;
m_autonomous = autonomous;
m_test = test;
m_eStop = eStop;
m_fmsAttached = fmsAttached;
m_dsAttached = dsAttached;
}
public boolean getEnabled() {
return m_enabled;
}
public boolean getAutonomous() {
return m_autonomous;
}
public boolean getTest() {
return m_test;
}
public boolean getEStop() {
return m_eStop;
}
public boolean getFMSAttached() {
return m_fmsAttached;
}
public boolean getDSAttached() {
return m_dsAttached;
}
}

View File

@@ -0,0 +1,12 @@
package edu.wpi.first.wpilibj.communication;
public class NIRioStatus {
// TODO: Should this file be auto-generated?
public static final int kRioStatusOffset = -63000;
public static final int kRioStatusSuccess = 0;
public static final int kRIOStatusBufferInvalidSize = kRioStatusOffset - 80;
public static final int kRIOStatusOperationTimedOut = -52007;
public static final int kRIOStatusFeatureNotSupported = kRioStatusOffset - 193;
public static final int kRIOStatusResourceNotInitialized = -52010;
}

View File

@@ -0,0 +1,18 @@
package edu.wpi.first.wpilibj.communication;
public class UsageReporting {
public static void report(int resource, int instanceNumber, int i) {
report(resource, instanceNumber, i, "");
}
public static void report(int resource, int instanceNumber) {
report(resource, instanceNumber, 0, "");
}
public static void report(int resource, int instanceNumber, int i, String string) {
FRCNetworkCommunicationsLibrary.FRCNetworkCommunicationUsageReportingReport((byte) resource,
(byte) instanceNumber, (byte) i, string);
}
}

View File

@@ -0,0 +1,13 @@
package edu.wpi.first.wpilibj.hal;
public class AccelerometerJNI extends JNIWrapper {
public static native void setAccelerometerActive(boolean active);
public static native void setAccelerometerRange(int range);
public static native double getAccelerometerX();
public static native double getAccelerometerY();
public static native double getAccelerometerZ();
}

View File

@@ -0,0 +1,113 @@
package edu.wpi.first.wpilibj.hal;
import java.nio.IntBuffer;
import java.nio.LongBuffer;
public class AnalogJNI extends JNIWrapper {
/**
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Analog.h:58</i><br>
* enum values
*/
public static interface AnalogTriggerType {
/**
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Analog.h:54</i>
*/
public static final int kInWindow = 0;
/**
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Analog.h:55</i>
*/
public static final int kState = 1;
/**
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Analog.h:56</i>
*/
public static final int kRisingPulse = 2;
/**
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Analog.h:57</i>
*/
public static final int kFallingPulse = 3;
};
public static native long initializeAnalogInputPort(long port_pointer);
public static native long initializeAnalogOutputPort(long port_pointer);
public static native boolean checkAnalogModule(byte module);
public static native boolean checkAnalogInputChannel(int pin);
public static native boolean checkAnalogOutputChannel(int pin);
public static native void setAnalogOutput(long port_pointer, double voltage);
public static native double getAnalogOutput(long port_pointer);
public static native void setAnalogSampleRate(double samplesPerSecond);
public static native double getAnalogSampleRate();
public static native void setAnalogAverageBits(long analog_port_pointer, int bits);
public static native int getAnalogAverageBits(long analog_port_pointer);
public static native void setAnalogOversampleBits(long analog_port_pointer, int bits);
public static native int getAnalogOversampleBits(long analog_port_pointer);
public static native short getAnalogValue(long analog_port_pointer);
public static native int getAnalogAverageValue(long analog_port_pointer);
public static native int getAnalogVoltsToValue(long analog_port_pointer, double voltage);
public static native double getAnalogVoltage(long analog_port_pointer);
public static native double getAnalogAverageVoltage(long analog_port_pointer);
public static native int getAnalogLSBWeight(long analog_port_pointer);
public static native int getAnalogOffset(long analog_port_pointer);
public static native boolean isAccumulatorChannel(long analog_port_pointer);
public static native void initAccumulator(long analog_port_pointer);
public static native void resetAccumulator(long analog_port_pointer);
public static native void setAccumulatorCenter(long analog_port_pointer, int center);
public static native void setAccumulatorDeadband(long analog_port_pointer, int deadband);
public static native long getAccumulatorValue(long analog_port_pointer);
public static native int getAccumulatorCount(long analog_port_pointer);
public static native void getAccumulatorOutput(long analog_port_pointer, LongBuffer value,
IntBuffer count);
public static native long initializeAnalogTrigger(long port_pointer, IntBuffer index);
public static native void cleanAnalogTrigger(long analog_trigger_pointer);
public static native void setAnalogTriggerLimitsRaw(long analog_trigger_pointer, int lower,
int upper);
public static native void setAnalogTriggerLimitsVoltage(long analog_trigger_pointer,
double lower, double upper);
public static native void setAnalogTriggerAveraged(long analog_trigger_pointer,
boolean useAveragedValue);
public static native void setAnalogTriggerFiltered(long analog_trigger_pointer,
boolean useFilteredValue);
public static native boolean getAnalogTriggerInWindow(long analog_trigger_pointer);
public static native boolean getAnalogTriggerTriggerState(long analog_trigger_pointer);
public static native boolean getAnalogTriggerOutput(long analog_trigger_pointer, int type);
}

View File

@@ -0,0 +1,556 @@
/*
* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org). Version
* 2.0.11
*$
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* -----------------------------------------------------------------------------
*/
package edu.wpi.first.wpilibj.hal;
public class CanTalonJNI {
public final static native long new_doublep();
public final static native long copy_doublep(double jarg1);
public final static native void delete_doublep(long jarg1);
public final static native void doublep_assign(long jarg1, double jarg2);
public final static native double doublep_value(long jarg1);
public final static native long new_intp();
public final static native long copy_intp(int jarg1);
public final static native void delete_intp(long jarg1);
public final static native void intp_assign(long jarg1, int jarg2);
public final static native int intp_value(long jarg1);
public final static native long new_uint32_tp();
public final static native long copy_uint32_tp(long jarg1);
public final static native void delete_uint32_tp(long jarg1);
public final static native void uint32_tp_assign(long jarg1, long jarg2);
public final static native long uint32_tp_value(long jarg1);
public final static native long new_int32_tp();
public final static native long copy_int32_tp(long jarg1);
public final static native void delete_int32_tp(long jarg1);
public final static native void int32_tp_assign(long jarg1, long jarg2);
public final static native long int32_tp_value(long jarg1);
public final static native long new_uint8_tp();
public final static native long copy_uint8_tp(long jarg1);
public final static native void delete_uint8_tp(long jarg1);
public final static native void uint8_tp_assign(long jarg1, long jarg2);
public final static native long uint8_tp_value(long jarg1);
public final static native long new_CTR_Codep();
public final static native long copy_CTR_Codep(long jarg1);
public final static native void delete_CTR_Codep(long jarg1);
public final static native void CTR_Codep_assign(long jarg1, long jarg2);
public final static native long CTR_Codep_value(long jarg1);
public final static native long new_floatp();
public final static native long copy_floatp(float jarg1);
public final static native void delete_floatp(long jarg1);
public final static native void floatp_assign(long jarg1, float jarg2);
public final static native float floatp_value(long jarg1);
public final static native long new_CtreCanNode(long jarg1);
public final static native void delete_CtreCanNode(long jarg1);
public final static native long CtreCanNode_GetDeviceNumber(long jarg1, CtreCanNode jarg1_);
public final static native int CanTalonSRX_kDefaultControlPeriodMs_get();
public final static native long new_CanTalonSRX__SWIG_0(int jarg1, int jarg2);
public final static native long new_CanTalonSRX__SWIG_1(int jarg1);
public final static native long new_CanTalonSRX__SWIG_2();
public final static native void delete_CanTalonSRX(long jarg1);
public final static native void CanTalonSRX_Set(long jarg1, CanTalonSRX jarg1_, double jarg2);
public final static native int CanTalonSRX_kMode_DutyCycle_get();
public final static native int CanTalonSRX_kMode_PositionCloseLoop_get();
public final static native int CanTalonSRX_kMode_VelocityCloseLoop_get();
public final static native int CanTalonSRX_kMode_CurrentCloseLoop_get();
public final static native int CanTalonSRX_kMode_VoltCompen_get();
public final static native int CanTalonSRX_kMode_SlaveFollower_get();
public final static native int CanTalonSRX_kMode_NoDrive_get();
public final static native int CanTalonSRX_kLimitSwitchOverride_UseDefaultsFromFlash_get();
public final static native int CanTalonSRX_kLimitSwitchOverride_DisableFwd_DisableRev_get();
public final static native int CanTalonSRX_kLimitSwitchOverride_DisableFwd_EnableRev_get();
public final static native int CanTalonSRX_kLimitSwitchOverride_EnableFwd_DisableRev_get();
public final static native int CanTalonSRX_kLimitSwitchOverride_EnableFwd_EnableRev_get();
public final static native int CanTalonSRX_kBrakeOverride_UseDefaultsFromFlash_get();
public final static native int CanTalonSRX_kBrakeOverride_OverrideCoast_get();
public final static native int CanTalonSRX_kBrakeOverride_OverrideBrake_get();
public final static native int CanTalonSRX_kFeedbackDev_DigitalQuadEnc_get();
public final static native int CanTalonSRX_kFeedbackDev_AnalogPot_get();
public final static native int CanTalonSRX_kFeedbackDev_AnalogEncoder_get();
public final static native int CanTalonSRX_kFeedbackDev_CountEveryRisingEdge_get();
public final static native int CanTalonSRX_kFeedbackDev_CountEveryFallingEdge_get();
public final static native int CanTalonSRX_kFeedbackDev_PosIsPulseWidth_get();
public final static native int CanTalonSRX_kProfileSlotSelect_Slot0_get();
public final static native int CanTalonSRX_kProfileSlotSelect_Slot1_get();
public final static native int CanTalonSRX_kStatusFrame_General_get();
public final static native int CanTalonSRX_kStatusFrame_Feedback_get();
public final static native int CanTalonSRX_kStatusFrame_Encoder_get();
public final static native int CanTalonSRX_kStatusFrame_AnalogTempVbat_get();
public final static native int CanTalonSRX_kStatusFrame_PulseWidthMeas_get();
public final static native int CanTalonSRX_eProfileParamSlot0_P_get();
public final static native int CanTalonSRX_eProfileParamSlot0_I_get();
public final static native int CanTalonSRX_eProfileParamSlot0_D_get();
public final static native int CanTalonSRX_eProfileParamSlot0_F_get();
public final static native int CanTalonSRX_eProfileParamSlot0_IZone_get();
public final static native int CanTalonSRX_eProfileParamSlot0_CloseLoopRampRate_get();
public final static native int CanTalonSRX_eProfileParamSlot1_P_get();
public final static native int CanTalonSRX_eProfileParamSlot1_I_get();
public final static native int CanTalonSRX_eProfileParamSlot1_D_get();
public final static native int CanTalonSRX_eProfileParamSlot1_F_get();
public final static native int CanTalonSRX_eProfileParamSlot1_IZone_get();
public final static native int CanTalonSRX_eProfileParamSlot1_CloseLoopRampRate_get();
public final static native int CanTalonSRX_eProfileParamSoftLimitForThreshold_get();
public final static native int CanTalonSRX_eProfileParamSoftLimitRevThreshold_get();
public final static native int CanTalonSRX_eProfileParamSoftLimitForEnable_get();
public final static native int CanTalonSRX_eProfileParamSoftLimitRevEnable_get();
public final static native int CanTalonSRX_eOnBoot_BrakeMode_get();
public final static native int CanTalonSRX_eOnBoot_LimitSwitch_Forward_NormallyClosed_get();
public final static native int CanTalonSRX_eOnBoot_LimitSwitch_Reverse_NormallyClosed_get();
public final static native int CanTalonSRX_eOnBoot_LimitSwitch_Forward_Disable_get();
public final static native int CanTalonSRX_eOnBoot_LimitSwitch_Reverse_Disable_get();
public final static native int CanTalonSRX_eFault_OverTemp_get();
public final static native int CanTalonSRX_eFault_UnderVoltage_get();
public final static native int CanTalonSRX_eFault_ForLim_get();
public final static native int CanTalonSRX_eFault_RevLim_get();
public final static native int CanTalonSRX_eFault_HardwareFailure_get();
public final static native int CanTalonSRX_eFault_ForSoftLim_get();
public final static native int CanTalonSRX_eFault_RevSoftLim_get();
public final static native int CanTalonSRX_eStckyFault_OverTemp_get();
public final static native int CanTalonSRX_eStckyFault_UnderVoltage_get();
public final static native int CanTalonSRX_eStckyFault_ForLim_get();
public final static native int CanTalonSRX_eStckyFault_RevLim_get();
public final static native int CanTalonSRX_eStckyFault_ForSoftLim_get();
public final static native int CanTalonSRX_eStckyFault_RevSoftLim_get();
public final static native int CanTalonSRX_eAppliedThrottle_get();
public final static native int CanTalonSRX_eCloseLoopErr_get();
public final static native int CanTalonSRX_eFeedbackDeviceSelect_get();
public final static native int CanTalonSRX_eRevMotDuringCloseLoopEn_get();
public final static native int CanTalonSRX_eModeSelect_get();
public final static native int CanTalonSRX_eProfileSlotSelect_get();
public final static native int CanTalonSRX_eRampThrottle_get();
public final static native int CanTalonSRX_eRevFeedbackSensor_get();
public final static native int CanTalonSRX_eLimitSwitchEn_get();
public final static native int CanTalonSRX_eLimitSwitchClosedFor_get();
public final static native int CanTalonSRX_eLimitSwitchClosedRev_get();
public final static native int CanTalonSRX_eSensorPosition_get();
public final static native int CanTalonSRX_eSensorVelocity_get();
public final static native int CanTalonSRX_eCurrent_get();
public final static native int CanTalonSRX_eBrakeIsEnabled_get();
public final static native int CanTalonSRX_eEncPosition_get();
public final static native int CanTalonSRX_eEncVel_get();
public final static native int CanTalonSRX_eEncIndexRiseEvents_get();
public final static native int CanTalonSRX_eQuadApin_get();
public final static native int CanTalonSRX_eQuadBpin_get();
public final static native int CanTalonSRX_eQuadIdxpin_get();
public final static native int CanTalonSRX_eAnalogInWithOv_get();
public final static native int CanTalonSRX_eAnalogInVel_get();
public final static native int CanTalonSRX_eTemp_get();
public final static native int CanTalonSRX_eBatteryV_get();
public final static native int CanTalonSRX_eResetCount_get();
public final static native int CanTalonSRX_eResetFlags_get();
public final static native int CanTalonSRX_eFirmVers_get();
public final static native int CanTalonSRX_eSettingsChanged_get();
public final static native int CanTalonSRX_eQuadFilterEn_get();
public final static native int CanTalonSRX_ePidIaccum_get();
public final static native int CanTalonSRX_eStatus1FrameRate_get();
public final static native int CanTalonSRX_eStatus2FrameRate_get();
public final static native int CanTalonSRX_eStatus3FrameRate_get();
public final static native int CanTalonSRX_eStatus4FrameRate_get();
public final static native int CanTalonSRX_eStatus6FrameRate_get();
public final static native int CanTalonSRX_eStatus7FrameRate_get();
public final static native int CanTalonSRX_eClearPositionOnIdx_get();
public final static native int CanTalonSRX_ePeakPosOutput_get();
public final static native int CanTalonSRX_eNominalPosOutput_get();
public final static native int CanTalonSRX_ePeakNegOutput_get();
public final static native int CanTalonSRX_eNominalNegOutput_get();
public final static native int CanTalonSRX_eQuadIdxPolarity_get();
public final static native int CanTalonSRX_eStatus8FrameRate_get();
public final static native int CanTalonSRX_eAllowPosOverflow_get();
public final static native int CanTalonSRX_eProfileParamSlot0_AllowableClosedLoopErr_get();
public final static native int CanTalonSRX_eNumberPotTurns_get();
public final static native int CanTalonSRX_eNumberEncoderCPR_get();
public final static native int CanTalonSRX_ePwdPosition_get();
public final static native int CanTalonSRX_eAinPosition_get();
public final static native int CanTalonSRX_eProfileParamVcompRate_get();
public final static native int CanTalonSRX_eProfileParamSlot1_AllowableClosedLoopErr_get();
public final static native long CanTalonSRX_SetParam(long jarg1, CanTalonSRX jarg1_, int jarg2,
double jarg3);
public final static native long CanTalonSRX_RequestParam(long jarg1, CanTalonSRX jarg1_, int jarg2);
public final static native long CanTalonSRX_GetParamResponse(long jarg1, CanTalonSRX jarg1_,
int jarg2, long jarg3);
public final static native long CanTalonSRX_GetParamResponseInt32(long jarg1, CanTalonSRX jarg1_,
int jarg2, long jarg3);
public final static native long CanTalonSRX_SetPgain(long jarg1, CanTalonSRX jarg1_, long jarg2,
double jarg3);
public final static native long CanTalonSRX_SetIgain(long jarg1, CanTalonSRX jarg1_, long jarg2,
double jarg3);
public final static native long CanTalonSRX_SetDgain(long jarg1, CanTalonSRX jarg1_, long jarg2,
double jarg3);
public final static native long CanTalonSRX_SetFgain(long jarg1, CanTalonSRX jarg1_, long jarg2,
double jarg3);
public final static native long CanTalonSRX_SetIzone(long jarg1, CanTalonSRX jarg1_, long jarg2,
int jarg3);
public final static native long CanTalonSRX_SetCloseLoopRampRate(long jarg1, CanTalonSRX jarg1_,
long jarg2, int jarg3);
public final static native long CanTalonSRX_SetSensorPosition(long jarg1, CanTalonSRX jarg1_,
int jarg2);
public final static native long CanTalonSRX_SetForwardSoftLimit(long jarg1, CanTalonSRX jarg1_,
int jarg2);
public final static native long CanTalonSRX_SetReverseSoftLimit(long jarg1, CanTalonSRX jarg1_,
int jarg2);
public final static native long CanTalonSRX_SetForwardSoftEnable(long jarg1, CanTalonSRX jarg1_,
int jarg2);
public final static native long CanTalonSRX_SetReverseSoftEnable(long jarg1, CanTalonSRX jarg1_,
int jarg2);
public final static native long CanTalonSRX_GetPgain(long jarg1, CanTalonSRX jarg1_, long jarg2,
long jarg3);
public final static native long CanTalonSRX_GetIgain(long jarg1, CanTalonSRX jarg1_, long jarg2,
long jarg3);
public final static native long CanTalonSRX_GetDgain(long jarg1, CanTalonSRX jarg1_, long jarg2,
long jarg3);
public final static native long CanTalonSRX_GetFgain(long jarg1, CanTalonSRX jarg1_, long jarg2,
long jarg3);
public final static native long CanTalonSRX_GetIzone(long jarg1, CanTalonSRX jarg1_, long jarg2,
long jarg3);
public final static native long CanTalonSRX_GetCloseLoopRampRate(long jarg1, CanTalonSRX jarg1_,
long jarg2, long jarg3);
public final static native long CanTalonSRX_GetVoltageCompensationRate(long jarg1,
CanTalonSRX jarg1_, long jarg2);
public final static native long CanTalonSRX_GetForwardSoftLimit(long jarg1, CanTalonSRX jarg1_,
long jarg2);
public final static native long CanTalonSRX_GetReverseSoftLimit(long jarg1, CanTalonSRX jarg1_,
long jarg2);
public final static native long CanTalonSRX_GetForwardSoftEnable(long jarg1, CanTalonSRX jarg1_,
long jarg2);
public final static native long CanTalonSRX_GetReverseSoftEnable(long jarg1, CanTalonSRX jarg1_,
long jarg2);
public final static native long CanTalonSRX_SetStatusFrameRate(long jarg1, CanTalonSRX jarg1_,
long jarg2, long jarg3);
public final static native long CanTalonSRX_ClearStickyFaults(long jarg1, CanTalonSRX jarg1_);
public final static native long CanTalonSRX_GetFault_OverTemp(long jarg1, CanTalonSRX jarg1_,
long jarg2);
public final static native long CanTalonSRX_GetFault_UnderVoltage(long jarg1, CanTalonSRX jarg1_,
long jarg2);
public final static native long CanTalonSRX_GetFault_ForLim(long jarg1, CanTalonSRX jarg1_,
long jarg2);
public final static native long CanTalonSRX_GetFault_RevLim(long jarg1, CanTalonSRX jarg1_,
long jarg2);
public final static native long CanTalonSRX_GetFault_HardwareFailure(long jarg1,
CanTalonSRX jarg1_, long jarg2);
public final static native long CanTalonSRX_GetFault_ForSoftLim(long jarg1, CanTalonSRX jarg1_,
long jarg2);
public final static native long CanTalonSRX_GetFault_RevSoftLim(long jarg1, CanTalonSRX jarg1_,
long jarg2);
public final static native long CanTalonSRX_GetStckyFault_OverTemp(long jarg1,
CanTalonSRX jarg1_, long jarg2);
public final static native long CanTalonSRX_GetStckyFault_UnderVoltage(long jarg1,
CanTalonSRX jarg1_, long jarg2);
public final static native long CanTalonSRX_GetStckyFault_ForLim(long jarg1, CanTalonSRX jarg1_,
long jarg2);
public final static native long CanTalonSRX_GetStckyFault_RevLim(long jarg1, CanTalonSRX jarg1_,
long jarg2);
public final static native long CanTalonSRX_GetStckyFault_ForSoftLim(long jarg1,
CanTalonSRX jarg1_, long jarg2);
public final static native long CanTalonSRX_GetStckyFault_RevSoftLim(long jarg1,
CanTalonSRX jarg1_, long jarg2);
public final static native long CanTalonSRX_GetAppliedThrottle(long jarg1, CanTalonSRX jarg1_,
long jarg2);
public final static native long CanTalonSRX_GetCloseLoopErr(long jarg1, CanTalonSRX jarg1_,
long jarg2);
public final static native long CanTalonSRX_GetFeedbackDeviceSelect(long jarg1,
CanTalonSRX jarg1_, long jarg2);
public final static native long CanTalonSRX_GetModeSelect(long jarg1, CanTalonSRX jarg1_,
long jarg2);
public final static native long CanTalonSRX_GetLimitSwitchEn(long jarg1, CanTalonSRX jarg1_,
long jarg2);
public final static native long CanTalonSRX_GetLimitSwitchClosedFor(long jarg1,
CanTalonSRX jarg1_, long jarg2);
public final static native long CanTalonSRX_GetLimitSwitchClosedRev(long jarg1,
CanTalonSRX jarg1_, long jarg2);
public final static native long CanTalonSRX_GetSensorPosition(long jarg1, CanTalonSRX jarg1_,
long jarg2);
public final static native long CanTalonSRX_GetSensorVelocity(long jarg1, CanTalonSRX jarg1_,
long jarg2);
public final static native long CanTalonSRX_GetCurrent(long jarg1, CanTalonSRX jarg1_, long jarg2);
public final static native long CanTalonSRX_GetBrakeIsEnabled(long jarg1, CanTalonSRX jarg1_,
long jarg2);
public final static native long CanTalonSRX_GetEncPosition(long jarg1, CanTalonSRX jarg1_,
long jarg2);
public final static native long CanTalonSRX_GetEncVel(long jarg1, CanTalonSRX jarg1_, long jarg2);
public final static native long CanTalonSRX_GetEncIndexRiseEvents(long jarg1, CanTalonSRX jarg1_,
long jarg2);
public final static native long CanTalonSRX_GetQuadApin(long jarg1, CanTalonSRX jarg1_, long jarg2);
public final static native long CanTalonSRX_GetQuadBpin(long jarg1, CanTalonSRX jarg1_, long jarg2);
public final static native long CanTalonSRX_GetQuadIdxpin(long jarg1, CanTalonSRX jarg1_,
long jarg2);
public final static native long CanTalonSRX_GetAnalogInWithOv(long jarg1, CanTalonSRX jarg1_,
long jarg2);
public final static native long CanTalonSRX_GetAnalogInVel(long jarg1, CanTalonSRX jarg1_,
long jarg2);
public final static native long CanTalonSRX_GetTemp(long jarg1, CanTalonSRX jarg1_, long jarg2);
public final static native long CanTalonSRX_GetBatteryV(long jarg1, CanTalonSRX jarg1_, long jarg2);
public final static native long CanTalonSRX_GetResetCount(long jarg1, CanTalonSRX jarg1_,
long jarg2);
public final static native long CanTalonSRX_GetResetFlags(long jarg1, CanTalonSRX jarg1_,
long jarg2);
public final static native long CanTalonSRX_GetFirmVers(long jarg1, CanTalonSRX jarg1_, long jarg2);
public final static native long CanTalonSRX_SetDemand(long jarg1, CanTalonSRX jarg1_, int jarg2);
public final static native long CanTalonSRX_SetOverrideLimitSwitchEn(long jarg1,
CanTalonSRX jarg1_, int jarg2);
public final static native long CanTalonSRX_SetFeedbackDeviceSelect(long jarg1,
CanTalonSRX jarg1_, int jarg2);
public final static native long CanTalonSRX_SetRevMotDuringCloseLoopEn(long jarg1,
CanTalonSRX jarg1_, int jarg2);
public final static native long CanTalonSRX_SetOverrideBrakeType(long jarg1, CanTalonSRX jarg1_,
int jarg2);
public final static native long CanTalonSRX_SetModeSelect(long jarg1, CanTalonSRX jarg1_,
int jarg2);
public final static native long CanTalonSRX_SetProfileSlotSelect(long jarg1, CanTalonSRX jarg1_,
int jarg2);
public final static native long CanTalonSRX_SetRampThrottle(long jarg1, CanTalonSRX jarg1_,
int jarg2);
public final static native long CanTalonSRX_SetVoltageCompensationRate(long jarg1, CanTalonSRX jarg1_,
double jarg2);
public final static native long CanTalonSRX_SetRevFeedbackSensor(long jarg1, CanTalonSRX jarg1_,
int jarg2);
public final static native long CanTalonSRX_GetPulseWidthPosition(long jarg1, CanTalonSRX jarg1_, long jarg2);
public final static native long CanTalonSRX_GetPulseWidthVelocity(long jarg1, CanTalonSRX jarg1_, long jarg2);
public final static native long CanTalonSRX_GetPulseWidthRiseToFallUs(long jarg1, CanTalonSRX jarg1_, long jarg2);
public final static native long CanTalonSRX_GetPulseWidthRiseToRiseUs(long jarg1, CanTalonSRX jarg1_, long jarg2);
public final static native long CanTalonSRX_IsPulseWidthSensorPresent(long jarg1, CanTalonSRX jarg1_, long jarg2);
public final static native long CanTalonSRX_SWIGUpcast(long jarg1);
}

View File

@@ -0,0 +1,31 @@
package edu.wpi.first.wpilibj.hal;
public class CompressorJNI extends JNIWrapper {
public static native long initializeCompressor(byte module);
public static native boolean checkCompressorModule(byte module);
public static native boolean getCompressor(long pcm_pointer);
public static native void setClosedLoopControl(long pcm_pointer, boolean value);
public static native boolean getClosedLoopControl(long pcm_pointer);
public static native boolean getPressureSwitch(long pcm_pointer);
public static native float getCompressorCurrent(long pcm_pointer);
public static native boolean getCompressorCurrentTooHighFault(long pcm_pointer);
public static native boolean getCompressorCurrentTooHighStickyFault(long pcm_pointer);
public static native boolean getCompressorShortedStickyFault(long pcm_pointer);
public static native boolean getCompressorShortedFault(long pcm_pointer);
public static native boolean getCompressorNotConnectedStickyFault(long pcm_pointer);
public static native boolean getCompressorNotConnectedFault(long pcm_pointer);
public static native void clearAllPCMStickyFaults(long pcm_pointer);
}

View File

@@ -0,0 +1,58 @@
package edu.wpi.first.wpilibj.hal;
import java.nio.IntBuffer;
public class CounterJNI extends JNIWrapper {
public static native long initializeCounter(int mode, IntBuffer index);
public static native void freeCounter(long counter_pointer);
public static native void setCounterAverageSize(long counter_pointer, int size);
public static native void setCounterUpSource(long counter_pointer, int pin,
boolean analogTrigger);
public static native void setCounterUpSourceEdge(long counter_pointer, boolean risingEdge,
boolean fallingEdge);
public static native void clearCounterUpSource(long counter_pointer);
public static native void setCounterDownSource(long counter_pointer, int pin,
boolean analogTrigger);
public static native void setCounterDownSourceEdge(long counter_pointer, boolean risingEdge,
boolean fallingEdge);
public static native void clearCounterDownSource(long counter_pointer);
public static native void setCounterUpDownMode(long counter_pointer);
public static native void setCounterExternalDirectionMode(long counter_pointer);
public static native void setCounterSemiPeriodMode(long counter_pointer,
boolean highSemiPeriod);
public static native void setCounterPulseLengthMode(long counter_pointer, double threshold);
public static native int getCounterSamplesToAverage(long counter_pointer);
public static native void setCounterSamplesToAverage(long counter_pointer,
int samplesToAverage);
public static native void resetCounter(long counter_pointer);
public static native int getCounter(long counter_pointer);
public static native double getCounterPeriod(long counter_pointer);
public static native void setCounterMaxPeriod(long counter_pointer, double maxPeriod);
public static native void setCounterUpdateWhenEmpty(long counter_pointer, boolean enabled);
public static native boolean getCounterStopped(long counter_pointer);
public static native boolean getCounterDirection(long counter_pointer);
public static native void setCounterReverseDirection(long counter_pointer,
boolean reverseDirection);
}

View File

@@ -0,0 +1,23 @@
package edu.wpi.first.wpilibj.hal;
public class DIOJNI extends JNIWrapper {
public static native long initializeDigitalPort(long port_pointer);
public static native boolean allocateDIO(long digital_port_pointer, boolean input);
public static native void freeDIO(long digital_port_pointer);
public static native void setDIO(long digital_port_pointer, short value);
public static native boolean getDIO(long digital_port_pointer);
public static native boolean getDIODirection(long digital_port_pointer);
public static native void pulse(long digital_port_pointer, double pulseLength);
public static native boolean isPulsing(long digital_port_pointer);
public static native boolean isAnyPulsing();
public static native short getLoopTiming();
}

View File

@@ -0,0 +1,34 @@
package edu.wpi.first.wpilibj.hal;
import java.nio.IntBuffer;
public class EncoderJNI extends JNIWrapper {
public static native long initializeEncoder(byte port_a_module, int port_a_pin,
boolean port_a_analog_trigger, byte port_b_module, int port_b_pin, boolean port_b_analog_trigger,
boolean reverseDirection, IntBuffer index);
public static native void freeEncoder(long encoder_pointer);
public static native void resetEncoder(long encoder_pointer);
public static native int getEncoder(long encoder_pointer);
public static native double getEncoderPeriod(long encoder_pointer);
public static native void setEncoderMaxPeriod(long encoder_pointer, double maxPeriod);
public static native boolean getEncoderStopped(long encoder_pointer);
public static native boolean getEncoderDirection(long encoder_pointer);
public static native void setEncoderReverseDirection(long encoder_pointer,
boolean reverseDirection);
public static native void setEncoderSamplesToAverage(long encoder_pointer,
int samplesToAverage);
public static native int getEncoderSamplesToAverage(long encoder_pointer);
public static native void setEncoderIndexSource(long digital_port, int pin,
boolean analogTrigger, boolean activeHigh, boolean edgeSensitive);
}

View File

@@ -0,0 +1,714 @@
package edu.wpi.first.wpilibj.hal;
// import com.ochafik.lang.jnaerator.runtime.LibraryExtractor;
// import com.ochafik.lang.jnaerator.runtime.MangledFunctionMapper;
// import com.ochafik.lang.jnaerator.runtime.globals.GlobalDouble;
// import com.ochafik.lang.jnaerator.runtime.globals.GlobalInt;
// import com.sun.jna.Callback;
// import com.sun.jna.Library;
// import com.sun.jna.Native;
// import com.sun.jna.NativeLibrary;
// import com.sun.jna.Pointer;
// import com.sun.jna.PointerType;
// import com.sun.jna.ptr.IntByReference;
// import com.sun.jna.ptr.LongByReference;
// import java.nio.IntBuffer;
/**
* JNA Wrapper for library <b>HAL</b><br>
* This file was autogenerated by <a
* href="http://jnaerator.googlecode.com/">JNAerator</a>,<br>
* a tool written by <a href="http://ochafik.com/">Olivier Chafik</a> that <a
* href="http://code.google.com/p/jnaerator/wiki/CreditsAndLicense">uses a few
* opensource projects.</a>.<br>
* For help, please visit <a
* href="http://nativelibs4java.googlecode.com/">NativeLibs4Java</a> , <a
* href="http://rococoa.dev.java.net/">Rococoa</a>, or <a
* href="http://jna.dev.java.net/">JNA</a>.
*/
public class HALLibrary /* implements Library */{
// public static final String JNA_LIBRARY_NAME =
// LibraryExtractor.getLibraryPath("HALAthenaJava", true, HALLibrary.class);
// public static final NativeLibrary JNA_NATIVE_LIB =
// NativeLibrary.getInstance(HALLibrary.JNA_LIBRARY_NAME,
// MangledFunctionMapper.DEFAULT_OPTIONS);
static {
System.loadLibrary("JNIWrappers");
// Native.register(HALLibrary.class, HALLibrary.JNA_NATIVE_LIB);
}
/**
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Digital.h:148</i><br>
* enum values
*/
public static interface Mode {
/**
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Digital.h:144</i>
*/
public static final int kTwoPulse = 0;
/**
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Digital.h:145</i>
*/
public static final int kSemiperiod = 1;
/**
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Digital.h:146</i>
*/
public static final int kPulseLength = 2;
/**
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Digital.h:147</i>
*/
public static final int kExternalDirection = 3;
};
/**
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Digital.h:235</i><br>
* enum values
*/
public static interface tSPIConstants {
/**
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Digital.h:233</i>
*/
public static final int kReceiveFIFODepth = 512;
/**
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Digital.h:234</i>
*/
public static final int kTransmitFIFODepth = 512;
};
/**
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Digital.h:241</i><br>
* enum values
*/
public static interface tFrameMode {
/**
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Digital.h:237</i>
*/
public static final int kChipSelect = 0;
/**
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Digital.h:238</i>
*/
public static final int kPreLatchPulse = 1;
/**
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Digital.h:239</i>
*/
public static final int kPostLatchPulse = 2;
/**
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Digital.h:240</i>
*/
public static final int kPreAndPostLatchPulse = 3;
};
/** <i>native declaration : AthenaJava\target\native\include\HAL\Errors.h</i> */
public static final String NULL_PARAMETER_MESSAGE = "A pointer parameter to a method is NULL";
/** <i>native declaration : AthenaJava\target\native\include\HAL\Errors.h</i> */
public static final String NO_AVAILABLE_RESOURCES_MESSAGE = "No available resources to allocate";
/** <i>native declaration : AthenaJava\target\native\include\HAL\Errors.h</i> */
public static final String INCOMPATIBLE_STATE_MESSAGE =
"Incompatible State: The operation cannot be completed";
/** <i>native declaration : AthenaJava\target\native\include\HAL\Errors.h</i> */
public static final String ANALOG_TRIGGER_PULSE_OUTPUT_ERROR_MESSAGE =
"Attempted to read AnalogTrigger pulse output.";
/** <i>native declaration : AthenaJava\target\native\include\HAL\Errors.h</i> */
public static final int ANALOG_TRIGGER_LIMIT_ORDER_ERROR = -10;
/** <i>native declaration : AthenaJava\target\native\include\HAL\Errors.h</i> */
public static final int SPI_READ_NO_DATA = 14;
/** <i>native declaration : AthenaJava\target\native\include\HAL\Errors.h</i> */
public static final String VOLTAGE_OUT_OF_RANGE_MESSAGE =
"Voltage to convert to raw value is out of range [-10; 10]";
/** <i>native declaration : AthenaJava\target\native\include\HAL\Errors.h</i> */
public static final String ANALOG_TRIGGER_LIMIT_ORDER_ERROR_MESSAGE =
"AnalogTrigger limits error. Lower limit > Upper Limit";
/** <i>native declaration : AthenaJava\target\native\include\HAL\Errors.h</i> */
public static final int SPI_WRITE_NO_MOSI = 12;
/** <i>native declaration : AthenaJava\target\native\include\HAL\Errors.h</i> */
public static final String PARAMETER_OUT_OF_RANGE_MESSAGE = "A parameter is out of range.";
/** <i>native declaration : AthenaJava\target\native\include\HAL\Task.h</i> */
public static final int OK = 0;
/** <i>native declaration : AthenaJava\target\native\include\HAL\Task.h</i> */
public static final int ERROR = (-1);
/** <i>native declaration : AthenaJava\target\native\include\HAL\Errors.h</i> */
public static final String SAMPLE_RATE_TOO_HIGH_MESSAGE = "Analog module sample rate is too high";
/** <i>native declaration : AthenaJava\target\native\include\HAL\Errors.h</i> */
public static final String SPI_WRITE_NO_MOSI_MESSAGE =
"Cannot write to SPI port with no MOSI output";
/** <i>native declaration : AthenaJava\target\native\include\HAL\Errors.h</i> */
public static final int SPI_READ_NO_MISO = 13;
/** <i>native declaration : AthenaJava\target\native\include\HAL\Errors.h</i> */
public static final String SPI_READ_NO_DATA_MESSAGE = "No data available to read from SPI";
/** <i>native declaration : AthenaJava\target\native\include\HAL\Errors.h</i> */
/** <i>native declaration : AthenaJava\target\native\include\HAL\Errors.h</i> */
public static final String SPI_READ_NO_MISO_MESSAGE =
"Cannot read from SPI port with no MISO input";
/** <i>native declaration : AthenaJava\target\native\include\HAL\Errors.h</i> */
public static final String LOOP_TIMING_ERROR_MESSAGE =
"Digital module loop timing is not the expected value";
/**
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Notifier.h:339</i>
*/
// public interface initializeNotifier_ProcessQueue_callback extends Callback
// {
// void apply(int uint32_t1, Pointer voidPtr1);
// };
/**
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Interrupts.h:342</i>
*/
/**
* <i>native declaration : AthenaJava\target\native\include\HAL\Task.h:409</i>
*/
// public interface FUNCPTR extends Callback {
// int apply(Object... varargs);
// };
/**
* Original signature : <code>bool checkPWMChannel(void*)</code><br>
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Digital.h:84</i>
*/
// public static native byte checkPWMChannel(Pointer digital_port_pointer);
/**
* Original signature : <code>bool checkRelayChannel(void*)</code><br>
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Digital.h:86</i>
*/
// public static native byte checkRelayChannel(Pointer digital_port_pointer);
/**
* Original signature :
* <code>void* initializeNotifier(initializeNotifier_ProcessQueue_callback*, int32_t*)</code>
* <br>
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Notifier.h:334</i><br>
*$
* @deprecated use the safer methods
* {@link #initializeNotifier(edu.wpi.first.wpilibj.hal.HALLibrary.initializeNotifier_ProcessQueue_callback, java.nio.IntBuffer)}
* and
* {@link #initializeNotifier(edu.wpi.first.wpilibj.hal.HALLibrary.initializeNotifier_ProcessQueue_callback, com.sun.jna.ptr.IntByReference)}
* instead
*/
// @Deprecated
// public static native Pointer
// initializeNotifier(HALLibrary.initializeNotifier_ProcessQueue_callback
// ProcessQueue, IntByReference status);
/**
* Original signature :
* <code>void* initializeNotifier(initializeNotifier_ProcessQueue_callback*, int32_t*)</code>
* <br>
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Notifier.h:334</i>
*/
// public static native Pointer
// initializeNotifier(HALLibrary.initializeNotifier_ProcessQueue_callback
// ProcessQueue, IntBuffer status);
/**
* Original signature : <code>void cleanNotifier(void*, int32_t*)</code><br>
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Notifier.h:336</i><br>
*$
* @deprecated use the safer methods
* {@link #cleanNotifier(com.sun.jna.Pointer, java.nio.IntBuffer)}
* and
* {@link #cleanNotifier(com.sun.jna.Pointer, com.sun.jna.ptr.IntByReference)}
* instead
*/
// @Deprecated
// public static native void cleanNotifier(Pointer notifier_pointer,
// IntByReference status);
/**
* Original signature : <code>void cleanNotifier(void*, int32_t*)</code><br>
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Notifier.h:336</i>
*/
// public static native void cleanNotifier(Pointer notifier_pointer, IntBuffer
// status);
/**
* Original signature :
* <code>void updateNotifierAlarm(void*, uint32_t, int32_t*)</code><br>
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Notifier.h:338</i><br>
*$
* @deprecated use the safer methods
* {@link #updateNotifierAlarm(com.sun.jna.Pointer, int, java.nio.IntBuffer)}
* and
* {@link #updateNotifierAlarm(com.sun.jna.Pointer, int, com.sun.jna.ptr.IntByReference)}
* instead
*/
// @Deprecated
// public static native void updateNotifierAlarm(Pointer notifier_pointer, int
// triggerTime, IntByReference status);
/**
* Original signature :
* <code>void updateNotifierAlarm(void*, uint32_t, int32_t*)</code><br>
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Notifier.h:338</i>
*/
// public static native void updateNotifierAlarm(Pointer notifier_pointer, int
// triggerTime, IntBuffer status);
/**
* Original signature : <code>void delayTicks(int32_t)</code><br>
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Utilities.h:366</i>
*/
public static native void delayTicks(int ticks);
/**
* Original signature : <code>void delayMillis(double)</code><br>
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Utilities.h:368</i>
*/
public static native void delayMillis(double ms);
/**
* Original signature : <code>void delaySeconds(double)</code><br>
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Utilities.h:370</i>
*/
public static native void delaySeconds(double s);
/**
* Original signature : <code>MUTEX_ID initializeMutex(uint32_t)</code><br>
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Semaphore.h:385</i>
*/
public static native long initializeMutex(int flags);
/**
* Original signature : <code>void deleteMutex(MUTEX_ID)</code><br>
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Semaphore.h:387</i><br>
*$
* @deprecated use the safer methods
* {@link #deleteMutex(edu.wpi.first.wpilibj.hal.HALLibrary.MUTEX_ID)}
* and {@link #deleteMutex(com.sun.jna.Pointer)} instead
*/
// @Deprecated
// public static native void deleteMutex(Pointer sem);
/**
* Original signature : <code>void deleteMutex(MUTEX_ID)</code><br>
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Semaphore.h:387</i>
*/
public static native void deleteMutex(long sem);
/**
* Original signature : <code>int8_t takeMutex(MUTEX_ID, int32_t)</code><br>
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Semaphore.h:389</i><br>
*$
* @deprecated use the safer methods
* {@link #takeMutex(edu.wpi.first.wpilibj.hal.HALLibrary.MUTEX_ID, int)}
* and {@link #takeMutex(com.sun.jna.Pointer, int)} instead
*/
// @Deprecated
// public static native byte takeMutex(Pointer sem, int timeout);
/**
* Original signature : <code>int8_t takeMutex(MUTEX_ID, int32_t)</code><br>
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Semaphore.h:389</i>
*/
public static native byte takeMutex(long sem, int timeout);
/**
* Original signature : <code>int8_t giveMutex(MUTEX_ID)</code><br>
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Semaphore.h:391</i><br>
*$
* @deprecated use the safer methods
* {@link #giveMutex(edu.wpi.first.wpilibj.hal.HALLibrary.MUTEX_ID)}
* and {@link #giveMutex(com.sun.jna.Pointer)} instead
*/
// @Deprecated
// public static native byte giveMutex(Pointer sem);
/**
* Original signature : <code>int8_t giveMutex(MUTEX_ID)</code><br>
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Semaphore.h:391</i>
*/
// public static native byte giveMutex(HALLibrary.MUTEX_ID sem);
/**
* Original signature :
* <code>SEMAPHORE_ID initializeSemaphore(uint32_t, uint32_t)</code><br>
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Semaphore.h:393</i>
*/
// public static native HALLibrary.SEMAPHORE_ID initializeSemaphore(int flags,
// int initial_value);
/**
* Original signature : <code>void deleteSemaphore(SEMAPHORE_ID)</code><br>
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Semaphore.h:395</i><br>
*$
* @deprecated use the safer methods
* {@link #deleteSemaphore(edu.wpi.first.wpilibj.hal.HALLibrary.SEMAPHORE_ID)}
* and {@link #deleteSemaphore(com.sun.jna.Pointer)} instead
*/
// @Deprecated
// public static native void deleteSemaphore(Pointer sem);
/**
* Original signature : <code>void deleteSemaphore(SEMAPHORE_ID)</code><br>
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Semaphore.h:395</i>
*/
// public static native void deleteSemaphore(HALLibrary.SEMAPHORE_ID sem);
/**
* Original signature :
* <code>int8_t takeSemaphore(SEMAPHORE_ID, int32_t)</code><br>
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Semaphore.h:397</i><br>
*$
* @deprecated use the safer methods
* {@link #takeSemaphore(edu.wpi.first.wpilibj.hal.HALLibrary.SEMAPHORE_ID, int)}
* and {@link #takeSemaphore(com.sun.jna.Pointer, int)} instead
*/
// @Deprecated
// public static native byte takeSemaphore(Pointer sem, int timeout);
/**
* Original signature :
* <code>int8_t takeSemaphore(SEMAPHORE_ID, int32_t)</code><br>
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Semaphore.h:397</i>
*/
// public static native byte takeSemaphore(HALLibrary.SEMAPHORE_ID sem, int
// timeout);
/**
* Original signature : <code>int8_t giveSemaphore(SEMAPHORE_ID)</code><br>
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Semaphore.h:399</i><br>
*$
* @deprecated use the safer methods
* {@link #giveSemaphore(edu.wpi.first.wpilibj.hal.HALLibrary.SEMAPHORE_ID)}
* and {@link #giveSemaphore(com.sun.jna.Pointer)} instead
*/
// @Deprecated
// public static native byte giveSemaphore(Pointer sem);
/**
* Original signature : <code>int8_t giveSemaphore(SEMAPHORE_ID)</code><br>
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Semaphore.h:399</i>
*/
// public static native byte giveSemaphore(HALLibrary.SEMAPHORE_ID sem);
/**
* Original signature : <code>MULTIWAIT_ID initializeMultiWait()</code><br>
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Semaphore.h:401</i>
*/
// public static native HALLibrary.MULTIWAIT_ID initializeMultiWait();
/**
* Original signature : <code>void deleteMultiWait(MULTIWAIT_ID)</code><br>
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Semaphore.h:403</i><br>
*$
* @deprecated use the safer methods
* {@link #deleteMultiWait(edu.wpi.first.wpilibj.hal.HALLibrary.MULTIWAIT_ID)}
* and {@link #deleteMultiWait(com.sun.jna.Pointer)} instead
*/
// @Deprecated
// public static native void deleteMultiWait(Pointer sem);
/**
* Original signature : <code>void deleteMultiWait(MULTIWAIT_ID)</code><br>
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Semaphore.h:403</i>
*/
// public static native void deleteMultiWait(HALLibrary.MULTIWAIT_ID sem);
/**
* Original signature :
* <code>int8_t takeMultiWait(MULTIWAIT_ID, int32_t)</code><br>
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Semaphore.h:405</i><br>
*$
* @deprecated use the safer methods
* {@link #takeMultiWait(edu.wpi.first.wpilibj.hal.HALLibrary.MULTIWAIT_ID, int)}
* and {@link #takeMultiWait(com.sun.jna.Pointer, int)} instead
*/
// @Deprecated
// public static native byte takeMultiWait(Pointer sem, int timeout);
/**
* Original signature :
* <code>int8_t takeMultiWait(MULTIWAIT_ID, int32_t)</code><br>
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Semaphore.h:405</i>
*/
// public static native byte takeMultiWait(HALLibrary.MULTIWAIT_ID sem, int
// timeout);
/**
* Original signature : <code>int8_t giveMultiWait(MULTIWAIT_ID)</code><br>
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Semaphore.h:407</i><br>
*$
* @deprecated use the safer methods
* {@link #giveMultiWait(edu.wpi.first.wpilibj.hal.HALLibrary.MULTIWAIT_ID)}
* and {@link #giveMultiWait(com.sun.jna.Pointer)} instead
*/
// @Deprecated
// public static native byte giveMultiWait(Pointer sem);
/**
* Original signature : <code>int8_t giveMultiWait(MULTIWAIT_ID)</code><br>
* <i>native declaration :
* AthenaJava\target\native\include\HAL\Semaphore.h:407</i>
*/
// public static native byte giveMultiWait(HALLibrary.MULTIWAIT_ID sem);
/**
* Original signature :
* <code>TASK spawnTask(char*, int, int, int, FUNCPTR, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t)</code>
* <br>
* <i>native declaration : AthenaJava\target\native\include\HAL\Task.h:420</i><br>
*$
* @deprecated use the safer methods
* {@link #spawnTask(java.nio.ByteBuffer, int, int, int, edu.wpi.first.wpilibj.hal.HALLibrary.FUNCPTR, int, int, int, int, int, int, int, int, int, int)}
* and
* {@link #spawnTask(com.sun.jna.Pointer, int, int, int, edu.wpi.first.wpilibj.hal.HALLibrary.FUNCPTR, int, int, int, int, int, int, int, int, int, int)}
* instead
*/
// @Deprecated
// public static native HALLibrary.TASK spawnTask(Pointer name, int priority,
// int options, int stackSize, HALLibrary.FUNCPTR entryPt, int arg0, int arg1,
// int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8, int
// arg9);
/**
* Original signature :
* <code>TASK spawnTask(char*, int, int, int, FUNCPTR, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t)</code>
* <br>
* <i>native declaration : AthenaJava\target\native\include\HAL\Task.h:420</i>
*/
// public static native HALLibrary.TASK spawnTask(ByteBuffer name, int
// priority, int options, int stackSize, HALLibrary.FUNCPTR entryPt, int arg0,
// int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int
// arg8, int arg9);
/**
* Original signature : <code>STATUS restartTask(TASK)</code><br>
* <i>native declaration : AthenaJava\target\native\include\HAL\Task.h:422</i><br>
*$
* @deprecated use the safer methods
* {@link #restartTask(edu.wpi.first.wpilibj.hal.HALLibrary.TASK)}
* and {@link #restartTask(com.sun.jna.Pointer)} instead
*/
// @Deprecated
// public static native int restartTask(Pointer task);
/**
* Original signature : <code>STATUS restartTask(TASK)</code><br>
* <i>native declaration : AthenaJava\target\native\include\HAL\Task.h:422</i>
*/
// public static native int restartTask(HALLibrary.TASK task);
/**
* Original signature : <code>STATUS deleteTask(TASK)</code><br>
* <i>native declaration : AthenaJava\target\native\include\HAL\Task.h:424</i><br>
*$
* @deprecated use the safer methods
* {@link #deleteTask(edu.wpi.first.wpilibj.hal.HALLibrary.TASK)}
* and {@link #deleteTask(com.sun.jna.Pointer)} instead
*/
// @Deprecated
// public static native int deleteTask(Pointer task);
/**
* Original signature : <code>STATUS deleteTask(TASK)</code><br>
* <i>native declaration : AthenaJava\target\native\include\HAL\Task.h:424</i>
*/
// public static native int deleteTask(HALLibrary.TASK task);
/**
* Original signature : <code>STATUS isTaskReady(TASK)</code><br>
* <i>native declaration : AthenaJava\target\native\include\HAL\Task.h:426</i><br>
*$
* @deprecated use the safer methods
* {@link #isTaskReady(edu.wpi.first.wpilibj.hal.HALLibrary.TASK)}
* and {@link #isTaskReady(com.sun.jna.Pointer)} instead
*/
// @Deprecated
// public static native int isTaskReady(Pointer task);
/**
* Original signature : <code>STATUS isTaskReady(TASK)</code><br>
* <i>native declaration : AthenaJava\target\native\include\HAL\Task.h:426</i>
*/
// public static native int isTaskReady(HALLibrary.TASK task);
/**
* Original signature : <code>STATUS isTaskSuspended(TASK)</code><br>
* <i>native declaration : AthenaJava\target\native\include\HAL\Task.h:428</i><br>
*$
* @deprecated use the safer methods
* {@link #isTaskSuspended(edu.wpi.first.wpilibj.hal.HALLibrary.TASK)}
* and {@link #isTaskSuspended(com.sun.jna.Pointer)} instead
*/
// @Deprecated
// public static native int isTaskSuspended(Pointer task);
/**
* Original signature : <code>STATUS isTaskSuspended(TASK)</code><br>
* <i>native declaration : AthenaJava\target\native\include\HAL\Task.h:428</i>
*/
// public static native int isTaskSuspended(HALLibrary.TASK task);
/**
* Original signature : <code>STATUS suspendTask(TASK)</code><br>
* <i>native declaration : AthenaJava\target\native\include\HAL\Task.h:430</i><br>
*$
* @deprecated use the safer methods
* {@link #suspendTask(edu.wpi.first.wpilibj.hal.HALLibrary.TASK)}
* and {@link #suspendTask(com.sun.jna.Pointer)} instead
*/
// @Deprecated
// public static native int suspendTask(Pointer task);
/**
* Original signature : <code>STATUS suspendTask(TASK)</code><br>
* <i>native declaration : AthenaJava\target\native\include\HAL\Task.h:430</i>
*/
// public static native int suspendTask(HALLibrary.TASK task);
/**
* Original signature : <code>STATUS resumeTask(TASK)</code><br>
* <i>native declaration : AthenaJava\target\native\include\HAL\Task.h:432</i><br>
*$
* @deprecated use the safer methods
* {@link #resumeTask(edu.wpi.first.wpilibj.hal.HALLibrary.TASK)}
* and {@link #resumeTask(com.sun.jna.Pointer)} instead
*/
// @Deprecated
// public static native int resumeTask(Pointer task);
/**
* Original signature : <code>STATUS resumeTask(TASK)</code><br>
* <i>native declaration : AthenaJava\target\native\include\HAL\Task.h:432</i>
*/
// public static native int resumeTask(HALLibrary.TASK task);
/**
* Original signature : <code>STATUS verifyTaskID(TASK)</code><br>
* <i>native declaration : AthenaJava\target\native\include\HAL\Task.h:434</i><br>
*$
* @deprecated use the safer methods
* {@link #verifyTaskID(edu.wpi.first.wpilibj.hal.HALLibrary.TASK)}
* and {@link #verifyTaskID(com.sun.jna.Pointer)} instead
*/
// @Deprecated
// public static native int verifyTaskID(Pointer task);
/**
* Original signature : <code>STATUS verifyTaskID(TASK)</code><br>
* <i>native declaration : AthenaJava\target\native\include\HAL\Task.h:434</i>
*/
// public static native int verifyTaskID(HALLibrary.TASK task);
/**
* Original signature : <code>STATUS setTaskPriority(TASK, int)</code><br>
* <i>native declaration : AthenaJava\target\native\include\HAL\Task.h:436</i><br>
*$
* @deprecated use the safer methods
* {@link #setTaskPriority(edu.wpi.first.wpilibj.hal.HALLibrary.TASK, int)}
* and {@link #setTaskPriority(com.sun.jna.Pointer, int)} instead
*/
// @Deprecated
// public static native int setTaskPriority(Pointer task, int priority);
/**
* Original signature : <code>STATUS setTaskPriority(TASK, int)</code><br>
* <i>native declaration : AthenaJava\target\native\include\HAL\Task.h:436</i>
*/
// public static native int setTaskPriority(HALLibrary.TASK task, int
// priority);
/**
* Original signature : <code>STATUS getTaskPriority(TASK, int*)</code><br>
* <i>native declaration : AthenaJava\target\native\include\HAL\Task.h:438</i><br>
*$
* @deprecated use the safer methods
* {@link #getTaskPriority(edu.wpi.first.wpilibj.hal.HALLibrary.TASK, java.nio.IntBuffer)}
* and
* {@link #getTaskPriority(com.sun.jna.Pointer, com.sun.jna.ptr.IntByReference)}
* instead
*/
// @Deprecated
// public static native int getTaskPriority(Pointer task, IntByReference
// priority);
/**
* Original signature : <code>STATUS getTaskPriority(TASK, int*)</code><br>
* <i>native declaration : AthenaJava\target\native\include\HAL\Task.h:438</i>
*/
// public static native int getTaskPriority(HALLibrary.TASK task, IntBuffer
// priority);
/**
* Original signature : <code>void* getPort(uint8_t)</code><br>
* <i>native declaration : AthenaJava\target\native\include\HAL\HAL.h:446</i>
*/
// public static native Pointer getPort(byte pin);
/**
* Original signature : <code>uint16_t getFPGAVersion(int32_t*)</code><br>
* <i>native declaration : AthenaJava\target\native\include\HAL\HAL.h:452</i><br>
*$
* @deprecated use the safer methods
* {@link #getFPGAVersion(java.nio.IntBuffer)} and
* {@link #getFPGAVersion(com.sun.jna.ptr.IntByReference)} instead
*/
// @Deprecated
// public static native short getFPGAVersion(IntByReference status);
/**
* Original signature : <code>uint16_t getFPGAVersion(int32_t*)</code><br>
* <i>native declaration : AthenaJava\target\native\include\HAL\HAL.h:452</i>
*/
// public static native short getFPGAVersion(IntBuffer status);
/**
* Original signature : <code>uint32_t getFPGARevision(int32_t*)</code><br>
* <i>native declaration : AthenaJava\target\native\include\HAL\HAL.h:454</i><br>
*$
* @deprecated use the safer methods
* {@link #getFPGARevision(java.nio.IntBuffer)} and
* {@link #getFPGARevision(com.sun.jna.ptr.IntByReference)}
* instead
*/
// @Deprecated
// public static native int getFPGARevision(IntByReference status);
/**
* Original signature : <code>uint32_t getFPGARevision(int32_t*)</code><br>
* <i>native declaration : AthenaJava\target\native\include\HAL\HAL.h:454</i>
*/
// public static native int getFPGARevision(IntBuffer status);
/**
* Original signature : <code>uint32_t getFPGATime(int32_t*)</code><br>
* <i>native declaration : AthenaJava\target\native\include\HAL\HAL.h:456</i><br>
*$
* @deprecated use the safer methods {@link #getFPGATime(java.nio.IntBuffer)}
* and {@link #getFPGATime(com.sun.jna.ptr.IntByReference)}
* instead
*/
// @Deprecated
// public static native int getFPGATime(IntByReference status);
/**
* Original signature : <code>uint32_t getFPGATime(int32_t*)</code><br>
* <i>native declaration : AthenaJava\target\native\include\HAL\HAL.h:456</i>
*/
// public static native int getFPGATime(IntBuffer status);
/**
* Original signature : <code>double testDouble(double)</code><br>
* <i>native declaration : AthenaJava\target\native\include\HAL\HAL.h:462</i>
*/
public static native double testDouble(double param);
/**
* Original signature : <code>int32_t testInt32(int32_t)</code><br>
* <i>native declaration : AthenaJava\target\native\include\HAL\HAL.h:464</i>
*/
public static native int testInt32(int param);
/**
* Original signature : <code>void NumericArrayResize()</code><br>
* <i>native declaration : AthenaJava\target\native\include\HAL\HAL.h:470</i>
*/
public static native void NumericArrayResize();
/**
* Original signature : <code>void RTSetCleanupProc()</code><br>
* <i>native declaration : AthenaJava\target\native\include\HAL\HAL.h:472</i>
*/
public static native void RTSetCleanupProc();
/**
* Original signature : <code>void EDVR_CreateReference()</code><br>
* <i>native declaration : AthenaJava\target\native\include\HAL\HAL.h:474</i>
*/
public static native void EDVR_CreateReference();
/**
* Original signature : <code>void Occur()</code><br>
* <i>native declaration : AthenaJava\target\native\include\HAL\HAL.h:476</i>
*/
public static native void Occur();
}

View File

@@ -0,0 +1,48 @@
package edu.wpi.first.wpilibj.hal;
public class HALUtil extends JNIWrapper {
public static final int NULL_PARAMETER = -1005;
public static final int SAMPLE_RATE_TOO_HIGH = 1001;
public static final int VOLTAGE_OUT_OF_RANGE = 1002;
public static final int LOOP_TIMING_ERROR = 1004;
public static final int INCOMPATIBLE_STATE = 1015;
public static final int ANALOG_TRIGGER_PULSE_OUTPUT_ERROR = -1011;
public static final int NO_AVAILABLE_RESOURCES = -104;
public static final int PARAMETER_OUT_OF_RANGE = -1028;
// public static final int SEMAPHORE_WAIT_FOREVER = -1;
// public static final int SEMAPHORE_Q_PRIORITY = 0x01;
public static native long initializeMutexNormal();
public static native void deleteMutex(long sem);
public static native void takeMutex(long sem);
// public static native long initializeSemaphore(int initialValue);
// public static native void deleteSemaphore(long sem);
// public static native byte takeSemaphore(long sem, int timeout);
public static native long initializeMultiWait();
public static native void deleteMultiWait(long sem);
public static native void takeMultiWait(long sem, long m);
public static native short getFPGAVersion();
public static native int getFPGARevision();
public static native long getFPGATime();
public static native boolean getFPGAButton();
public static native String getHALErrorMessage(int code);
public static native int getHALErrno();
public static native String getHALstrerror(int errno);
public static String getHALstrerror() {
return getHALstrerror(getHALErrno());
}
}

View File

@@ -0,0 +1,17 @@
package edu.wpi.first.wpilibj.hal;
import java.nio.ByteBuffer;
public class I2CJNI extends JNIWrapper {
public static native void i2CInitialize(byte port);
public static native int i2CTransaction(byte port, byte address, ByteBuffer dataToSend,
byte sendSize, ByteBuffer dataReceived, byte receiveSize);
public static native int i2CWrite(byte port, byte address, ByteBuffer dataToSend, byte sendSize);
public static native int i2CRead(byte port, byte address, ByteBuffer dataRecieved,
byte receiveSize);
public static native void i2CClose(byte port);
}

View File

@@ -0,0 +1,31 @@
package edu.wpi.first.wpilibj.hal;
public class InterruptJNI extends JNIWrapper {
public interface InterruptJNIHandlerFunction {
void apply(int interruptAssertedMask, Object param);
};
public static native long initializeInterrupts(int interruptIndex, boolean watcher);
public static native void cleanInterrupts(long interrupt_pointer);
public static native int waitForInterrupt(long interrupt_pointer, double timeout,
boolean ignorePrevious);
public static native void enableInterrupts(long interrupt_pointer);
public static native void disableInterrupts(long interrupt_pointer);
public static native double readRisingTimestamp(long interrupt_pointer);
public static native double readFallingTimestamp(long interrupt_pointer);
public static native void requestInterrupts(long interrupt_pointer, byte routing_module,
int routing_pin, boolean routing_analog_trigger);
public static native void attachInterruptHandler(long interrupt_pointer,
InterruptJNIHandlerFunction handler, Object param);
public static native void setInterruptUpSourceEdge(long interrupt_pointer, boolean risingEdge,
boolean fallingEdge);
}

View File

@@ -0,0 +1,54 @@
package edu.wpi.first.wpilibj.hal;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileOutputStream;
//
// base class for all JNI wrappers
//
public class JNIWrapper {
static boolean libraryLoaded = false;
static File jniLibrary = null;
static {
try {
if (!libraryLoaded) {
// create temporary file
jniLibrary = File.createTempFile("libwpilibJavaJNI", ".so");
// flag for delete on exit
jniLibrary.deleteOnExit();
byte[] buffer = new byte[1024];
int readBytes;
InputStream is = JNIWrapper.class.getResourceAsStream("/linux-arm/libwpilibJavaJNI.so");
OutputStream os = new FileOutputStream(jniLibrary);
try {
while ((readBytes = is.read(buffer)) != -1) {
os.write(buffer, 0, readBytes);
}
} finally {
os.close();
is.close();
}
libraryLoaded = true;
}
System.load(jniLibrary.getAbsolutePath());
} catch (Exception ex) {
ex.printStackTrace();
System.exit(1);
}
}
public static native long getPortWithModule(byte module, byte pin);
public static native long getPort(byte pin);
}

View File

@@ -0,0 +1,29 @@
package edu.wpi.first.wpilibj.hal;
import java.lang.Runtime;
/**
* The NotifierJNI class directly wraps the C++ HAL Notifier.
*
* This class is not meant for direct use by teams. Instead, the
* edu.wpi.first.wpilibj.Notifier class, which corresponds to the C++ Notifier
* class, should be used.
*/
public class NotifierJNI extends JNIWrapper {
/**
* Initializes the notifier to call the run() function of a Runnable.
*
* Should be called after initializeNotifierJVM().
*/
public static native long initializeNotifier(Runnable func);
/**
* Deletes the notifier object when we are done with it.
*/
public static native void cleanNotifier(long notifierPtr);
/**
* Sets the notifier to call the callback in another triggerTime microseconds.
*/
public static native void updateNotifierAlarm(long notifierPtr, int triggerTime);
}

View File

@@ -0,0 +1,21 @@
package edu.wpi.first.wpilibj.hal;
public class PDPJNI extends JNIWrapper {
public static native void initializePDP(int module);
public static native double getPDPTemperature(int module);
public static native double getPDPVoltage(int module);
public static native double getPDPChannelCurrent(byte channel, int module);
public static native double getPDPTotalCurrent(int module);
public static native double getPDPTotalPower(int module);
public static native double getPDPTotalEnergy(int module);
public static native void resetPDPTotalEnergy(int module);
public static native void clearPDPStickyFaults(int module);
}

View File

@@ -0,0 +1,25 @@
package edu.wpi.first.wpilibj.hal;
public class PWMJNI extends DIOJNI {
public static native boolean allocatePWMChannel(long digital_port_pointer);
public static native void freePWMChannel(long digital_port_pointer);
public static native void setPWM(long digital_port_pointer, short value);
public static native short getPWM(long digital_port_pointer);
public static native void latchPWMZero(long digital_port_pointer);
public static native void setPWMPeriodScale(long digital_port_pointer, int squelchMask);
public static native long allocatePWM();
public static native void freePWM(long pwmGenerator);
public static native void setPWMRate(double rate);
public static native void setPWMDutyCycle(long pwmGenerator, double dutyCycle);
public static native void setPWMOutputChannel(long pwmGenerator, int pin);
}

View File

@@ -0,0 +1,31 @@
package edu.wpi.first.wpilibj.hal;
public class PowerJNI extends JNIWrapper {
public static native float getVinVoltage();
public static native float getVinCurrent();
public static native float getUserVoltage6V();
public static native float getUserCurrent6V();
public static native boolean getUserActive6V();
public static native int getUserCurrentFaults6V();
public static native float getUserVoltage5V();
public static native float getUserCurrent5V();
public static native boolean getUserActive5V();
public static native int getUserCurrentFaults5V();
public static native float getUserVoltage3V3();
public static native float getUserCurrent3V3();
public static native boolean getUserActive3V3();
public static native int getUserCurrentFaults3V3();
}

View File

@@ -0,0 +1,11 @@
package edu.wpi.first.wpilibj.hal;
public class RelayJNI extends DIOJNI {
public static native void setRelayForward(long digital_port_pointer, boolean on);
public static native void setRelayReverse(long digital_port_pointer, boolean on);
public static native boolean getRelayForward(long digital_port_pointer);
public static native boolean getRelayReverse(long digital_port_pointer);
}

View File

@@ -0,0 +1,27 @@
package edu.wpi.first.wpilibj.hal;
import java.nio.ByteBuffer;
public class SPIJNI extends JNIWrapper {
public static native void spiInitialize(byte port);
public static native int spiTransaction(byte port, ByteBuffer dataToSend,
ByteBuffer dataReceived, byte size);
public static native int spiWrite(byte port, ByteBuffer dataToSend, byte sendSize);
public static native int spiRead(byte port, ByteBuffer dataReceived, byte size);
public static native void spiClose(byte port);
public static native void spiSetSpeed(byte port, int speed);
public static native void spiSetBitsPerWord(byte port, byte bpw);
public static native void spiSetOpts(byte port, int msb_first, int sample_on_trailing,
int clk_idle_high);
public static native void spiSetChipSelectActiveHigh(byte port);
public static native void spiSetChipSelectActiveLow(byte port);
}

View File

@@ -0,0 +1,41 @@
package edu.wpi.first.wpilibj.hal;
import java.nio.ByteBuffer;
public class SerialPortJNI extends JNIWrapper {
public static native void serialInitializePort(byte port);
public static native void serialSetBaudRate(byte port, int baud);
public static native void serialSetDataBits(byte port, byte bits);
public static native void serialSetParity(byte port, byte parity);
public static native void serialSetStopBits(byte port, byte stopBits);
public static native void serialSetWriteMode(byte port, byte mode);
public static native void serialSetFlowControl(byte port, byte flow);
public static native void serialSetTimeout(byte port, float timeout);
public static native void serialEnableTermination(byte port, char terminator);
public static native void serialDisableTermination(byte port);
public static native void serialSetReadBufferSize(byte port, int size);
public static native void serialSetWriteBufferSize(byte port, int size);
public static native int serialGetBytesRecieved(byte port);
public static native int serialRead(byte port, ByteBuffer buffer, int count);
public static native int serialWrite(byte port, ByteBuffer buffer, int count);
public static native void serialFlush(byte port);
public static native void serialClear(byte port);
public static native void serialClose(byte port);
}

View File

@@ -0,0 +1,19 @@
package edu.wpi.first.wpilibj.hal;
public class SolenoidJNI extends JNIWrapper {
public static native long initializeSolenoidPort(long portPointer);
public static native long getPortWithModule(byte module, byte channel);
public static native void setSolenoid(long port, boolean on);
public static native boolean getSolenoid(long port);
public static native int getPCMSolenoidBlackList(long pcm_pointer);
public static native boolean getPCMSolenoidVoltageStickyFault(long pcm_pointer);
public static native boolean getPCMSolenoidVoltageFault(long pcm_pointer);
public static native void clearAllPCMStickyFaults(long pcm_pointer);
}

Some files were not shown because too many files have changed in this diff Show More