New 2018 and later build setup (#1001)

This commit is contained in:
Thad House
2018-04-29 13:29:07 -07:00
committed by Peter Johnson
parent cb2c9eb6d5
commit 7f88cf768d
317 changed files with 60521 additions and 54781 deletions

View File

@@ -42,7 +42,7 @@ public class AnalogInput extends SensorBase implements PIDSource, Sendable {
checkAnalogInputChannel(channel);
m_channel = channel;
final int portHandle = AnalogJNI.getPort((byte) channel);
final int portHandle = HAL.getPort((byte) channel);
m_port = AnalogJNI.initializeAnalogInputPort(portHandle);
HAL.report(tResourceType.kResourceType_AnalogChannel, channel);

View File

@@ -28,7 +28,7 @@ public class AnalogOutput extends SendableBase implements Sendable {
SensorBase.checkAnalogOutputChannel(channel);
m_channel = channel;
final int portHandle = AnalogJNI.getPort((byte) channel);
final int portHandle = HAL.getPort((byte) channel);
m_port = AnalogJNI.initializeAnalogOutputPort(portHandle);
HAL.report(tResourceType.kResourceType_AnalogOutput, channel);

View File

@@ -1,776 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2016-2018 FIRST. 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.cscore.AxisCamera;
import edu.wpi.cscore.CameraServerJNI;
import edu.wpi.cscore.CvSink;
import edu.wpi.cscore.CvSource;
import edu.wpi.cscore.MjpegServer;
import edu.wpi.cscore.UsbCamera;
import edu.wpi.cscore.VideoEvent;
import edu.wpi.cscore.VideoException;
import edu.wpi.cscore.VideoListener;
import edu.wpi.cscore.VideoMode;
import edu.wpi.cscore.VideoMode.PixelFormat;
import edu.wpi.cscore.VideoProperty;
import edu.wpi.cscore.VideoSink;
import edu.wpi.cscore.VideoSource;
import edu.wpi.first.wpilibj.hal.FRCNetComm.tResourceType;
import edu.wpi.first.wpilibj.hal.HAL;
import edu.wpi.first.networktables.EntryListenerFlags;
import edu.wpi.first.networktables.NetworkTable;
import edu.wpi.first.networktables.NetworkTableEntry;
import edu.wpi.first.networktables.NetworkTableInstance;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.ArrayList;
import java.util.Hashtable;
/**
* Singleton class for creating and keeping camera servers.
* Also publishes camera information to NetworkTables.
*/
public class CameraServer {
public static final int kBasePort = 1181;
@Deprecated
public static final int kSize640x480 = 0;
@Deprecated
public static final int kSize320x240 = 1;
@Deprecated
public static final int kSize160x120 = 2;
private static final String kPublishName = "/CameraPublisher";
private static CameraServer server;
/**
* Get the CameraServer instance.
*/
public static synchronized CameraServer getInstance() {
if (server == null) {
server = new CameraServer();
}
return server;
}
private AtomicInteger m_defaultUsbDevice;
private String m_primarySourceName;
private final Hashtable<String, VideoSource> m_sources;
private final Hashtable<String, VideoSink> m_sinks;
private final Hashtable<Integer, NetworkTable> m_tables; // indexed by source handle
private final NetworkTable m_publishTable;
private final VideoListener m_videoListener; //NOPMD
private final int m_tableListener; //NOPMD
private int m_nextPort;
private String[] m_addresses;
@SuppressWarnings("JavadocMethod")
private static String makeSourceValue(int source) {
switch (VideoSource.getKindFromInt(CameraServerJNI.getSourceKind(source))) {
case kUsb:
return "usb:" + CameraServerJNI.getUsbCameraPath(source);
case kHttp: {
String[] urls = CameraServerJNI.getHttpCameraUrls(source);
if (urls.length > 0) {
return "ip:" + urls[0];
} else {
return "ip:";
}
}
case kCv:
// FIXME: Should be "cv:", but LabVIEW dashboard requires "usb:".
// https://github.com/wpilibsuite/allwpilib/issues/407
return "usb:";
default:
return "unknown:";
}
}
@SuppressWarnings("JavadocMethod")
private static String makeStreamValue(String address, int port) {
return "mjpg:http://" + address + ":" + port + "/?action=stream";
}
@SuppressWarnings({"JavadocMethod", "PMD.AvoidUsingHardCodedIP"})
private synchronized String[] getSinkStreamValues(int sink) {
// Ignore all but MjpegServer
if (VideoSink.getKindFromInt(CameraServerJNI.getSinkKind(sink)) != VideoSink.Kind.kMjpeg) {
return new String[0];
}
// Get port
int port = CameraServerJNI.getMjpegServerPort(sink);
// Generate values
ArrayList<String> values = new ArrayList<>(m_addresses.length + 1);
String listenAddress = CameraServerJNI.getMjpegServerListenAddress(sink);
if (!listenAddress.isEmpty()) {
// If a listen address is specified, only use that
values.add(makeStreamValue(listenAddress, port));
} else {
// Otherwise generate for hostname and all interface addresses
values.add(makeStreamValue(CameraServerJNI.getHostname() + ".local", port));
for (String addr : m_addresses) {
if (addr.equals("127.0.0.1")) {
continue; // ignore localhost
}
values.add(makeStreamValue(addr, port));
}
}
return values.toArray(new String[0]);
}
@SuppressWarnings({"JavadocMethod", "PMD.AvoidUsingHardCodedIP"})
private synchronized String[] getSourceStreamValues(int source) {
// Ignore all but HttpCamera
if (VideoSource.getKindFromInt(CameraServerJNI.getSourceKind(source))
!= VideoSource.Kind.kHttp) {
return new String[0];
}
// Generate values
String[] values = CameraServerJNI.getHttpCameraUrls(source);
for (int j = 0; j < values.length; j++) {
values[j] = "mjpg:" + values[j];
}
// Look to see if we have a passthrough server for this source
for (VideoSink i : m_sinks.values()) {
int sink = i.getHandle();
int sinkSource = CameraServerJNI.getSinkSource(sink);
if (source == sinkSource
&& VideoSink.getKindFromInt(CameraServerJNI.getSinkKind(sink)) == VideoSink.Kind.kMjpeg) {
// Add USB-only passthrough
String[] finalValues = new String[values.length + 1];
for (int j = 0; j < values.length; j++) {
finalValues[j] = values[j];
}
int port = CameraServerJNI.getMjpegServerPort(sink);
finalValues[values.length] = makeStreamValue("172.22.11.2", port);
return finalValues;
}
}
return values;
}
@SuppressWarnings({"JavadocMethod", "PMD.AvoidUsingHardCodedIP"})
private synchronized void updateStreamValues() {
// Over all the sinks...
for (VideoSink i : m_sinks.values()) {
int sink = i.getHandle();
// Get the source's subtable (if none exists, we're done)
int source = CameraServerJNI.getSinkSource(sink);
if (source == 0) {
continue;
}
NetworkTable table = m_tables.get(source);
if (table != null) {
// Don't set stream values if this is a HttpCamera passthrough
if (VideoSource.getKindFromInt(CameraServerJNI.getSourceKind(source))
== VideoSource.Kind.kHttp) {
continue;
}
// Set table value
String[] values = getSinkStreamValues(sink);
if (values.length > 0) {
table.getEntry("streams").setStringArray(values);
}
}
}
// Over all the sources...
for (VideoSource i : m_sources.values()) {
int source = i.getHandle();
// Get the source's subtable (if none exists, we're done)
NetworkTable table = m_tables.get(source);
if (table != null) {
// Set table value
String[] values = getSourceStreamValues(source);
if (values.length > 0) {
table.getEntry("streams").setStringArray(values);
}
}
}
}
@SuppressWarnings("JavadocMethod")
private static String pixelFormatToString(PixelFormat pixelFormat) {
switch (pixelFormat) {
case kMJPEG:
return "MJPEG";
case kYUYV:
return "YUYV";
case kRGB565:
return "RGB565";
case kBGR:
return "BGR";
case kGray:
return "Gray";
default:
return "Unknown";
}
}
/// Provide string description of video mode.
/// The returned string is "{width}x{height} {format} {fps} fps".
@SuppressWarnings("JavadocMethod")
private static String videoModeToString(VideoMode mode) {
return mode.width + "x" + mode.height + " " + pixelFormatToString(mode.pixelFormat)
+ " " + mode.fps + " fps";
}
@SuppressWarnings("JavadocMethod")
private static String[] getSourceModeValues(int sourceHandle) {
VideoMode[] modes = CameraServerJNI.enumerateSourceVideoModes(sourceHandle);
String[] modeStrings = new String[modes.length];
for (int i = 0; i < modes.length; i++) {
modeStrings[i] = videoModeToString(modes[i]);
}
return modeStrings;
}
@SuppressWarnings("JavadocMethod")
private static void putSourcePropertyValue(NetworkTable table, VideoEvent event, boolean isNew) {
String name;
String infoName;
if (event.name.startsWith("raw_")) {
name = "RawProperty/" + event.name;
infoName = "RawPropertyInfo/" + event.name;
} else {
name = "Property/" + event.name;
infoName = "PropertyInfo/" + event.name;
}
NetworkTableEntry entry = table.getEntry(name);
try {
switch (event.propertyKind) {
case kBoolean:
if (isNew) {
entry.setDefaultBoolean(event.value != 0);
} else {
entry.setBoolean(event.value != 0);
}
break;
case kInteger:
case kEnum:
if (isNew) {
entry.setDefaultDouble(event.value);
table.getEntry(infoName + "/min").setDouble(
CameraServerJNI.getPropertyMin(event.propertyHandle));
table.getEntry(infoName + "/max").setDouble(
CameraServerJNI.getPropertyMax(event.propertyHandle));
table.getEntry(infoName + "/step").setDouble(
CameraServerJNI.getPropertyStep(event.propertyHandle));
table.getEntry(infoName + "/default").setDouble(
CameraServerJNI.getPropertyDefault(event.propertyHandle));
} else {
entry.setDouble(event.value);
}
break;
case kString:
if (isNew) {
entry.setDefaultString(event.valueStr);
} else {
entry.setString(event.valueStr);
}
break;
default:
break;
}
} catch (VideoException ex) {
// ignore
}
}
@SuppressWarnings({"JavadocMethod", "PMD.UnusedLocalVariable"})
private CameraServer() {
m_defaultUsbDevice = new AtomicInteger();
m_sources = new Hashtable<>();
m_sinks = new Hashtable<>();
m_tables = new Hashtable<>();
m_publishTable = NetworkTableInstance.getDefault().getTable(kPublishName);
m_nextPort = kBasePort;
m_addresses = new String[0];
// We publish sources to NetworkTables using the following structure:
// "/CameraPublisher/{Source.Name}/" - root
// - "source" (string): Descriptive, prefixed with type (e.g. "usb:0")
// - "streams" (string array): URLs that can be used to stream data
// - "description" (string): Description of the source
// - "connected" (boolean): Whether source is connected
// - "mode" (string): Current video mode
// - "modes" (string array): Available video modes
// - "Property/{Property}" - Property values
// - "PropertyInfo/{Property}" - Property supporting information
// Listener for video events
m_videoListener = new VideoListener(event -> {
switch (event.kind) {
case kSourceCreated: {
// Create subtable for the camera
NetworkTable table = m_publishTable.getSubTable(event.name);
m_tables.put(event.sourceHandle, table);
table.getEntry("source").setString(makeSourceValue(event.sourceHandle));
table.getEntry("description").setString(
CameraServerJNI.getSourceDescription(event.sourceHandle));
table.getEntry("connected").setBoolean(
CameraServerJNI.isSourceConnected(event.sourceHandle));
table.getEntry("streams").setStringArray(getSourceStreamValues(event.sourceHandle));
try {
VideoMode mode = CameraServerJNI.getSourceVideoMode(event.sourceHandle);
table.getEntry("mode").setDefaultString(videoModeToString(mode));
table.getEntry("modes").setStringArray(getSourceModeValues(event.sourceHandle));
} catch (VideoException ex) {
// Do nothing. Let the other event handlers update this if there is an error.
}
break;
}
case kSourceDestroyed: {
NetworkTable table = m_tables.get(event.sourceHandle);
if (table != null) {
table.getEntry("source").setString("");
table.getEntry("streams").setStringArray(new String[0]);
table.getEntry("modes").setStringArray(new String[0]);
}
break;
}
case kSourceConnected: {
NetworkTable table = m_tables.get(event.sourceHandle);
if (table != null) {
// update the description too (as it may have changed)
table.getEntry("description").setString(
CameraServerJNI.getSourceDescription(event.sourceHandle));
table.getEntry("connected").setBoolean(true);
}
break;
}
case kSourceDisconnected: {
NetworkTable table = m_tables.get(event.sourceHandle);
if (table != null) {
table.getEntry("connected").setBoolean(false);
}
break;
}
case kSourceVideoModesUpdated: {
NetworkTable table = m_tables.get(event.sourceHandle);
if (table != null) {
table.getEntry("modes").setStringArray(getSourceModeValues(event.sourceHandle));
}
break;
}
case kSourceVideoModeChanged: {
NetworkTable table = m_tables.get(event.sourceHandle);
if (table != null) {
table.getEntry("mode").setString(videoModeToString(event.mode));
}
break;
}
case kSourcePropertyCreated: {
NetworkTable table = m_tables.get(event.sourceHandle);
if (table != null) {
putSourcePropertyValue(table, event, true);
}
break;
}
case kSourcePropertyValueUpdated: {
NetworkTable table = m_tables.get(event.sourceHandle);
if (table != null) {
putSourcePropertyValue(table, event, false);
}
break;
}
case kSourcePropertyChoicesUpdated: {
NetworkTable table = m_tables.get(event.sourceHandle);
if (table != null) {
try {
String[] choices = CameraServerJNI.getEnumPropertyChoices(event.propertyHandle);
table.getEntry("PropertyInfo/" + event.name + "/choices").setStringArray(choices);
} catch (VideoException ex) {
// ignore
}
}
break;
}
case kSinkSourceChanged:
case kSinkCreated:
case kSinkDestroyed:
case kNetworkInterfacesChanged: {
m_addresses = CameraServerJNI.getNetworkInterfaces();
updateStreamValues();
break;
}
default:
break;
}
}, 0x4fff, true);
// Listener for NetworkTable events
// We don't currently support changing settings via NT due to
// synchronization issues, so just update to current setting if someone
// else tries to change it.
m_tableListener = NetworkTableInstance.getDefault().addEntryListener(kPublishName + "/",
(event) -> {
String relativeKey = event.name.substring(kPublishName.length() + 1);
// get source (sourceName/...)
int subKeyIndex = relativeKey.indexOf('/');
if (subKeyIndex == -1) {
return;
}
String sourceName = relativeKey.substring(0, subKeyIndex);
VideoSource source = m_sources.get(sourceName);
if (source == null) {
return;
}
// get subkey
relativeKey = relativeKey.substring(subKeyIndex + 1);
// handle standard names
String propName;
if (relativeKey.equals("mode")) {
// reset to current mode
event.getEntry().setString(videoModeToString(source.getVideoMode()));
return;
} else if (relativeKey.startsWith("Property/")) {
propName = relativeKey.substring(9);
} else if (relativeKey.startsWith("RawProperty/")) {
propName = relativeKey.substring(12);
} else {
return; // ignore
}
// everything else is a property
VideoProperty property = source.getProperty(propName);
switch (property.getKind()) {
case kNone:
return;
case kBoolean:
// reset to current setting
event.getEntry().setBoolean(property.get() != 0);
return;
case kInteger:
case kEnum:
// reset to current setting
event.getEntry().setDouble(property.get());
return;
case kString:
// reset to current setting
event.getEntry().setString(property.getString());
return;
default:
return;
}
}, EntryListenerFlags.kImmediate | EntryListenerFlags.kUpdate);
}
/**
* Start automatically capturing images to send to the dashboard.
*
* <p>You should call this method to see a camera feed on the dashboard.
* If you also want to perform vision processing on the roboRIO, use
* getVideo() to get access to the camera images.
*
* <p>The first time this overload is called, it calls
* {@link #startAutomaticCapture(int)} with device 0, creating a camera
* named "USB Camera 0". Subsequent calls increment the device number
* (e.g. 1, 2, etc).
*/
public UsbCamera startAutomaticCapture() {
UsbCamera camera = startAutomaticCapture(m_defaultUsbDevice.getAndIncrement());
HAL.report(tResourceType.kResourceType_PCVideoServer, camera.getHandle());
return camera;
}
/**
* Start automatically capturing images to send to the dashboard.
*
* <p>This overload calls {@link #startAutomaticCapture(String, int)} with
* a name of "USB Camera {dev}".
*
* @param dev The device number of the camera interface
*/
public UsbCamera startAutomaticCapture(int dev) {
UsbCamera camera = new UsbCamera("USB Camera " + dev, dev);
startAutomaticCapture(camera);
HAL.report(tResourceType.kResourceType_PCVideoServer, camera.getHandle());
return camera;
}
/**
* Start automatically capturing images to send to the dashboard.
*
* @param name The name to give the camera
* @param dev The device number of the camera interface
*/
public UsbCamera startAutomaticCapture(String name, int dev) {
UsbCamera camera = new UsbCamera(name, dev);
startAutomaticCapture(camera);
HAL.report(tResourceType.kResourceType_PCVideoServer, camera.getHandle());
return camera;
}
/**
* Start automatically capturing images to send to the dashboard.
*
* @param name The name to give the camera
* @param path The device path (e.g. "/dev/video0") of the camera
*/
public UsbCamera startAutomaticCapture(String name, String path) {
UsbCamera camera = new UsbCamera(name, path);
startAutomaticCapture(camera);
HAL.report(tResourceType.kResourceType_PCVideoServer, camera.getHandle());
return camera;
}
/**
* Start automatically capturing images to send to the dashboard from
* an existing camera.
*
* @param camera Camera
*/
public void startAutomaticCapture(VideoSource camera) {
addCamera(camera);
VideoSink server = addServer("serve_" + camera.getName());
server.setSource(camera);
}
/**
* Adds an Axis IP camera.
*
* <p>This overload calls {@link #addAxisCamera(String, String)} with
* name "Axis Camera".
*
* @param host Camera host IP or DNS name (e.g. "10.x.y.11")
*/
public AxisCamera addAxisCamera(String host) {
return addAxisCamera("Axis Camera", host);
}
/**
* Adds an Axis IP camera.
*
* <p>This overload calls {@link #addAxisCamera(String, String[])} with
* name "Axis Camera".
*
* @param hosts Array of Camera host IPs/DNS names
*/
public AxisCamera addAxisCamera(String[] hosts) {
return addAxisCamera("Axis Camera", hosts);
}
/**
* Adds an Axis IP camera.
*
* @param name The name to give the camera
* @param host Camera host IP or DNS name (e.g. "10.x.y.11")
*/
public AxisCamera addAxisCamera(String name, String host) {
AxisCamera camera = new AxisCamera(name, host);
// Create a passthrough MJPEG server for USB access
startAutomaticCapture(camera);
HAL.report(tResourceType.kResourceType_AxisCamera, camera.getHandle());
return camera;
}
/**
* Adds an Axis IP camera.
*
* @param name The name to give the camera
* @param hosts Array of Camera host IPs/DNS names
*/
public AxisCamera addAxisCamera(String name, String[] hosts) {
AxisCamera camera = new AxisCamera(name, hosts);
// Create a passthrough MJPEG server for USB access
startAutomaticCapture(camera);
HAL.report(tResourceType.kResourceType_AxisCamera, camera.getHandle());
return camera;
}
/**
* Get OpenCV access to the primary camera feed. This allows you to
* get images from the camera for image processing on the roboRIO.
*
* <p>This is only valid to call after a camera feed has been added
* with startAutomaticCapture() or addServer().
*/
public CvSink getVideo() {
VideoSource source;
synchronized (this) {
if (m_primarySourceName == null) {
throw new VideoException("no camera available");
}
source = m_sources.get(m_primarySourceName);
}
if (source == null) {
throw new VideoException("no camera available");
}
return getVideo(source);
}
/**
* Get OpenCV access to the specified camera. This allows you to get
* images from the camera for image processing on the roboRIO.
*
* @param camera Camera (e.g. as returned by startAutomaticCapture).
*/
public CvSink getVideo(VideoSource camera) {
String name = "opencv_" + camera.getName();
synchronized (this) {
VideoSink sink = m_sinks.get(name);
if (sink != null) {
VideoSink.Kind kind = sink.getKind();
if (kind != VideoSink.Kind.kCv) {
throw new VideoException("expected OpenCV sink, but got " + kind);
}
return (CvSink) sink;
}
}
CvSink newsink = new CvSink(name);
newsink.setSource(camera);
addServer(newsink);
return newsink;
}
/**
* Get OpenCV access to the specified camera. This allows you to get
* images from the camera for image processing on the roboRIO.
*
* @param name Camera name
*/
public CvSink getVideo(String name) {
VideoSource source;
synchronized (this) {
source = m_sources.get(name);
if (source == null) {
throw new VideoException("could not find camera " + name);
}
}
return getVideo(source);
}
/**
* Create a MJPEG stream with OpenCV input. This can be called to pass custom
* annotated images to the dashboard.
*
* @param name Name to give the stream
* @param width Width of the image being sent
* @param height Height of the image being sent
*/
public CvSource putVideo(String name, int width, int height) {
CvSource source = new CvSource(name, VideoMode.PixelFormat.kMJPEG, width, height, 30);
startAutomaticCapture(source);
return source;
}
/**
* Adds a MJPEG server at the next available port.
*
* @param name Server name
*/
public MjpegServer addServer(String name) {
int port;
synchronized (this) {
port = m_nextPort;
m_nextPort++;
}
return addServer(name, port);
}
/**
* Adds a MJPEG server.
*
* @param name Server name
*/
public MjpegServer addServer(String name, int port) {
MjpegServer server = new MjpegServer(name, port);
addServer(server);
return server;
}
/**
* Adds an already created server.
*
* @param server Server
*/
public void addServer(VideoSink server) {
synchronized (this) {
m_sinks.put(server.getName(), server);
}
}
/**
* Removes a server by name.
*
* @param name Server name
*/
public void removeServer(String name) {
synchronized (this) {
m_sinks.remove(name);
}
}
/**
* Get server for the primary camera feed.
*
* <p>This is only valid to call after a camera feed has been added
* with startAutomaticCapture() or addServer().
*/
public VideoSink getServer() {
synchronized (this) {
if (m_primarySourceName == null) {
throw new VideoException("no camera available");
}
return getServer("serve_" + m_primarySourceName);
}
}
/**
* Gets a server by name.
*
* @param name Server name
*/
public VideoSink getServer(String name) {
synchronized (this) {
return m_sinks.get(name);
}
}
/**
* Adds an already created camera.
*
* @param camera Camera
*/
public void addCamera(VideoSource camera) {
String name = camera.getName();
synchronized (this) {
if (m_primarySourceName == null) {
m_primarySourceName = name;
}
m_sources.put(name, camera);
}
}
/**
* Removes a camera by name.
*
* @param name Camera name
*/
public void removeCamera(String name) {
synchronized (this) {
m_sources.remove(name);
}
}
}

View File

@@ -31,7 +31,7 @@ public class DigitalInput extends DigitalSource implements Sendable {
checkDigitalChannel(channel);
m_channel = channel;
m_handle = DIOJNI.initializeDIOPort(DIOJNI.getPort((byte) channel), true);
m_handle = DIOJNI.initializeDIOPort(HAL.getPort((byte) channel), true);
HAL.report(tResourceType.kResourceType_DigitalInput, channel);
setName("DigitalInput", channel);

View File

@@ -34,7 +34,7 @@ public class DigitalOutput extends SendableBase implements Sendable {
SensorBase.checkDigitalChannel(channel);
m_channel = channel;
m_handle = DIOJNI.initializeDIOPort(DIOJNI.getPort((byte) channel), false);
m_handle = DIOJNI.initializeDIOPort(HAL.getPort((byte) channel), false);
HAL.report(tResourceType.kResourceType_DigitalOutput, channel);
setName("DigitalOutput", channel);

View File

@@ -58,11 +58,11 @@ public class DoubleSolenoid extends SolenoidBase implements Sendable {
SensorBase.checkSolenoidChannel(forwardChannel);
SensorBase.checkSolenoidChannel(reverseChannel);
int portHandle = SolenoidJNI.getPortWithModule((byte) m_moduleNumber, (byte) forwardChannel);
int portHandle = HAL.getPortWithModule((byte) m_moduleNumber, (byte) forwardChannel);
m_forwardHandle = SolenoidJNI.initializeSolenoidPort(portHandle);
try {
portHandle = SolenoidJNI.getPortWithModule((byte) m_moduleNumber, (byte) reverseChannel);
portHandle = HAL.getPortWithModule((byte) m_moduleNumber, (byte) reverseChannel);
m_reverseHandle = SolenoidJNI.initializeSolenoidPort(portHandle);
} catch (RuntimeException ex) {
// free the forward handle on exception, then rethrow

View File

@@ -7,7 +7,6 @@
package edu.wpi.first.wpilibj;
import edu.wpi.first.wpilibj.hal.DIOJNI;
import edu.wpi.first.wpilibj.hal.FRCNetComm.tResourceType;
import edu.wpi.first.wpilibj.hal.HAL;
import edu.wpi.first.wpilibj.hal.PWMJNI;
@@ -56,7 +55,7 @@ public class PWM extends SendableBase implements Sendable {
SensorBase.checkPWMChannel(channel);
m_channel = channel;
m_handle = PWMJNI.initializePWMPort(DIOJNI.getPort((byte) channel));
m_handle = PWMJNI.initializePWMPort(HAL.getPort((byte) channel));
setDisabled();

View File

@@ -102,7 +102,7 @@ public class Relay extends SendableBase implements MotorSafety, Sendable {
private void initRelay() {
SensorBase.checkRelayChannel(m_channel);
int portHandle = RelayJNI.getPort((byte) m_channel);
int portHandle = HAL.getPort((byte) m_channel);
if (m_direction == Direction.kBoth || m_direction == Direction.kForward) {
m_forwardHandle = RelayJNI.initializeRelayPort(portHandle, true);
HAL.report(tResourceType.kResourceType_Relay, m_channel);

View File

@@ -44,6 +44,38 @@ public abstract class RobotBase {
// This is usually 1, but it is best to make sure
public static final long MAIN_THREAD_ID = Thread.currentThread().getId();
private static void setupCameraServerShared() {
CameraServerShared shared = new CameraServerShared() {
@Override
public void reportVideoServer(int id) {
HAL.report(tResourceType.kResourceType_PCVideoServer, id);
}
@Override
public void reportUsbCamera(int id) {
HAL.report(tResourceType.kResourceType_PCVideoServer, id);
}
@Override
public void reportDriverStationError(String error) {
DriverStation.reportError(error, true);
}
@Override
public void reportAxisCamera(int id) {
HAL.report(tResourceType.kResourceType_AxisCamera, id);
}
@Override
public Long getRobotMainThreadId() {
return MAIN_THREAD_ID;
}
};
CameraServerSharedStore.setCameraServerShared(shared);
}
protected final DriverStation m_ds;
/**
@@ -57,6 +89,7 @@ public abstract class RobotBase {
*/
protected RobotBase() {
NetworkTableInstance inst = NetworkTableInstance.getDefault();
setupCameraServerShared();
inst.setNetworkIdentity("Robot");
inst.startServer("/home/lvuser/networktables.ini");
m_ds = DriverStation.getInstance();

View File

@@ -44,7 +44,7 @@ public class Solenoid extends SolenoidBase implements Sendable {
SensorBase.checkSolenoidModule(m_moduleNumber);
SensorBase.checkSolenoidChannel(m_channel);
int portHandle = SolenoidJNI.getPortWithModule((byte) m_moduleNumber, (byte) m_channel);
int portHandle = HAL.getPortWithModule((byte) m_moduleNumber, (byte) m_channel);
m_solenoidHandle = SolenoidJNI.initializeSolenoidPort(portHandle);
HAL.report(tResourceType.kResourceType_Solenoid, m_channel, m_moduleNumber);

View File

@@ -1,44 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2008-2018 FIRST. 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;
@SuppressWarnings("JavadocMethod")
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

@@ -1,22 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2008-2018 FIRST. 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();
}
public CANInvalidBufferException(String msg) {
super(msg);
}
}

View File

@@ -1,36 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2016-2018 FIRST. 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 java.nio.ByteBuffer;
import java.nio.IntBuffer;
import edu.wpi.first.wpilibj.hal.JNIWrapper;
@SuppressWarnings("AbbreviationAsWordInName")
public class CANJNI extends JNIWrapper {
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;
@SuppressWarnings("MethodName")
public static native void FRCNetCommCANSessionMuxSendMessage(int messageID,
byte[] data,
int periodMs);
@SuppressWarnings("MethodName")
public static native byte[] FRCNetCommCANSessionMuxReceiveMessage(
IntBuffer messageID, int messageIDMask, ByteBuffer timeStamp);
@SuppressWarnings("MethodName")
public static native void GetCANStatus(CANStatus status);
}

View File

@@ -1,18 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2008-2018 FIRST. 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

@@ -1,22 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2008-2018 FIRST. 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();
}
public CANMessageNotFoundException(String msg) {
super(msg);
}
}

View File

@@ -1,22 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2008-2018 FIRST. 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();
}
public CANNotInitializedException(String msg) {
super(msg);
}
}

View File

@@ -1,53 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2017-2018 FIRST. 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;
/**
* Structure for holding the result of a CAN Status request.
*/
public class CANStatus {
/**
* The utilization of the CAN Bus.
*/
@SuppressWarnings("MemberName")
public double percentBusUtilization;
/**
* The CAN Bus off count.
*/
@SuppressWarnings("MemberName")
public int busOffCount;
/**
* The CAN Bus TX full count.
*/
@SuppressWarnings("MemberName")
public int txFullCount;
/**
* The CAN Bus receive error count.
*/
@SuppressWarnings("MemberName")
public int receiveErrorCount;
/**
* The CAN Bus transmit error count.
*/
@SuppressWarnings("MemberName")
public int transmitErrorCount;
@SuppressWarnings("JavadocMethod")
public void setStatus(double percentBusUtilization, int busOffCount, int txFullCount,
int receiveErrorCount, int transmitErrorCount) {
this.percentBusUtilization = percentBusUtilization;
this.busOffCount = busOffCount;
this.txFullCount = txFullCount;
this.receiveErrorCount = receiveErrorCount;
this.transmitErrorCount = transmitErrorCount;
}
}

View File

@@ -1,19 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2016-2018 FIRST. 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.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

@@ -1,20 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2016-2018 FIRST. 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.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

@@ -1,12 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2016-2018 FIRST. 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.hal;
public enum AllianceStationID {
Red1, Red2, Red3, Blue1, Blue2, Blue3
}

View File

@@ -1,37 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2016-2018 FIRST. 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.hal;
public class AnalogGyroJNI extends JNIWrapper {
public static native int initializeAnalogGyro(int halAnalogInputHandle);
public static native void setupAnalogGyro(int handle);
public static native void freeAnalogGyro(int handle);
public static native void setAnalogGyroParameters(int handle,
double voltsPerDegreePerSecond,
double offset, int center);
public static native void setAnalogGyroVoltsPerDegreePerSecond(int handle,
double voltsPerDegreePerSecond);
public static native void resetAnalogGyro(int handle);
public static native void calibrateAnalogGyro(int handle);
public static native void setAnalogGyroDeadband(int handle, double volts);
public static native double getAnalogGyroAngle(int handle);
public static native double getAnalogGyroRate(int handle);
public static native double getAnalogGyroOffset(int handle);
public static native int getAnalogGyroCenter(int handle);
}

View File

@@ -1,117 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2016-2018 FIRST. 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.hal;
import edu.wpi.first.wpilibj.AccumulatorResult;
import java.nio.IntBuffer;
public class AnalogJNI extends JNIWrapper {
/**
* <i>native declaration : AthenaJava\target\native\include\HAL\Analog.h:58</i><br> enum values
*/
public interface AnalogTriggerType {
/**
* <i>native declaration : AthenaJava\target\native\include\HAL\Analog.h:54</i>
*/
int kInWindow = 0;
/**
* <i>native declaration : AthenaJava\target\native\include\HAL\Analog.h:55</i>
*/
int kState = 1;
/**
* <i>native declaration : AthenaJava\target\native\include\HAL\Analog.h:56</i>
*/
int kRisingPulse = 2;
/**
* <i>native declaration : AthenaJava\target\native\include\HAL\Analog.h:57</i>
*/
int kFallingPulse = 3;
}
public static native int initializeAnalogInputPort(int halPortHandle);
public static native void freeAnalogInputPort(int portHandle);
public static native int initializeAnalogOutputPort(int halPortHandle);
public static native void freeAnalogOutputPort(int portHandle);
public static native boolean checkAnalogModule(byte module);
public static native boolean checkAnalogInputChannel(int channel);
public static native boolean checkAnalogOutputChannel(int channel);
public static native void setAnalogOutput(int portHandle, double voltage);
public static native double getAnalogOutput(int portHandle);
public static native void setAnalogSampleRate(double samplesPerSecond);
public static native double getAnalogSampleRate();
public static native void setAnalogAverageBits(int analogPortHandle, int bits);
public static native int getAnalogAverageBits(int analogPortHandle);
public static native void setAnalogOversampleBits(int analogPortHandle, int bits);
public static native int getAnalogOversampleBits(int analogPortHandle);
public static native short getAnalogValue(int analogPortHandle);
public static native int getAnalogAverageValue(int analogPortHandle);
public static native int getAnalogVoltsToValue(int analogPortHandle, double voltage);
public static native double getAnalogVoltage(int analogPortHandle);
public static native double getAnalogAverageVoltage(int analogPortHandle);
public static native int getAnalogLSBWeight(int analogPortHandle);
public static native int getAnalogOffset(int analogPortHandle);
public static native boolean isAccumulatorChannel(int analogPortHandle);
public static native void initAccumulator(int analogPortHandle);
public static native void resetAccumulator(int analogPortHandle);
public static native void setAccumulatorCenter(int analogPortHandle, int center);
public static native void setAccumulatorDeadband(int analogPortHandle, int deadband);
public static native long getAccumulatorValue(int analogPortHandle);
public static native int getAccumulatorCount(int analogPortHandle);
public static native void getAccumulatorOutput(int analogPortHandle, AccumulatorResult result);
public static native int initializeAnalogTrigger(int analogInputHandle, IntBuffer index);
public static native void cleanAnalogTrigger(int analogTriggerHandle);
public static native void setAnalogTriggerLimitsRaw(int analogTriggerHandle, int lower,
int upper);
public static native void setAnalogTriggerLimitsVoltage(int analogTriggerHandle,
double lower, double upper);
public static native void setAnalogTriggerAveraged(int analogTriggerHandle,
boolean useAveragedValue);
public static native void setAnalogTriggerFiltered(int analogTriggerHandle,
boolean useFilteredValue);
public static native boolean getAnalogTriggerInWindow(int analogTriggerHandle);
public static native boolean getAnalogTriggerTriggerState(int analogTriggerHandle);
public static native boolean getAnalogTriggerOutput(int analogTriggerHandle, int type);
}

View File

@@ -1,38 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2016-2018 FIRST. 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.hal;
public class CompressorJNI extends JNIWrapper {
public static native int initializeCompressor(byte module);
public static native boolean checkCompressorModule(byte module);
public static native boolean getCompressor(int compressorHandle);
public static native void setCompressorClosedLoopControl(int compressorHandle, boolean value);
public static native boolean getCompressorClosedLoopControl(int compressorHandle);
public static native boolean getCompressorPressureSwitch(int compressorHandle);
public static native double getCompressorCurrent(int compressorHandle);
public static native boolean getCompressorCurrentTooHighFault(int compressorHandle);
public static native boolean getCompressorCurrentTooHighStickyFault(int compressorHandle);
public static native boolean getCompressorShortedStickyFault(int compressorHandle);
public static native boolean getCompressorShortedFault(int compressorHandle);
public static native boolean getCompressorNotConnectedStickyFault(int compressorHandle);
public static native boolean getCompressorNotConnectedFault(int compressorHandle);
public static native void clearAllPCMStickyFaults(byte compressorModule);
}

View File

@@ -1,12 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2016-2018 FIRST. 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.hal;
public class ConstantsJNI extends JNIWrapper {
public static native int getSystemClockTicksPerMicrosecond();
}

View File

@@ -1,54 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2016-2018 FIRST. 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.hal;
/**
* A wrapper for the HALControlWord bitfield.
*/
public class ControlWord {
private boolean m_enabled;
private boolean m_autonomous;
private boolean m_test;
private boolean m_emergencyStop;
private boolean m_fmsAttached;
private boolean m_dsAttached;
void update(boolean enabled, boolean autonomous, boolean test, boolean emergencyStop,
boolean fmsAttached, boolean dsAttached) {
m_enabled = enabled;
m_autonomous = autonomous;
m_test = test;
m_emergencyStop = emergencyStop;
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_emergencyStop;
}
public boolean getFMSAttached() {
return m_fmsAttached;
}
public boolean getDSAttached() {
return m_dsAttached;
}
}

View File

@@ -1,65 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2016-2018 FIRST. 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.hal;
import java.nio.IntBuffer;
public class CounterJNI extends JNIWrapper {
public static native int initializeCounter(int mode, IntBuffer index);
public static native void freeCounter(int counterHandle);
public static native void setCounterAverageSize(int counterHandle, int size);
public static native void setCounterUpSource(int counterHandle, int digitalSourceHandle,
int analogTriggerType);
public static native void setCounterUpSourceEdge(int counterHandle, boolean risingEdge,
boolean fallingEdge);
public static native void clearCounterUpSource(int counterHandle);
public static native void setCounterDownSource(int counterHandle, int digitalSourceHandle,
int analogTriggerType);
public static native void setCounterDownSourceEdge(int counterHandle, boolean risingEdge,
boolean fallingEdge);
public static native void clearCounterDownSource(int counterHandle);
public static native void setCounterUpDownMode(int counterHandle);
public static native void setCounterExternalDirectionMode(int counterHandle);
public static native void setCounterSemiPeriodMode(int counterHandle,
boolean highSemiPeriod);
public static native void setCounterPulseLengthMode(int counterHandle, double threshold);
public static native int getCounterSamplesToAverage(int counterHandle);
public static native void setCounterSamplesToAverage(int counterHandle,
int samplesToAverage);
public static native void resetCounter(int counterHandle);
public static native int getCounter(int counterHandle);
public static native double getCounterPeriod(int counterHandle);
public static native void setCounterMaxPeriod(int counterHandle, double maxPeriod);
public static native void setCounterUpdateWhenEmpty(int counterHandle, boolean enabled);
public static native boolean getCounterStopped(int counterHandle);
public static native boolean getCounterDirection(int counterHandle);
public static native void setCounterReverseDirection(int counterHandle,
boolean reverseDirection);
}

View File

@@ -1,44 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2016-2018 FIRST. 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.hal;
@SuppressWarnings("AbbreviationAsWordInName")
public class DIOJNI extends JNIWrapper {
public static native int initializeDIOPort(int halPortHandle, boolean input);
public static native boolean checkDIOChannel(int channel);
public static native void freeDIOPort(int dioPortHandle);
// TODO(Thad): Switch this to use boolean
public static native void setDIO(int dioPortHandle, short value);
public static native void setDIODirection(int dioPortHandle, boolean input);
public static native boolean getDIO(int dioPortHandle);
public static native boolean getDIODirection(int dioPortHandle);
public static native void pulse(int dioPortHandle, double pulseLength);
public static native boolean isPulsing(int dioPortHandle);
public static native boolean isAnyPulsing();
public static native short getLoopTiming();
public static native int allocateDigitalPWM();
public static native void freeDigitalPWM(int pwmGenerator);
public static native void setDigitalPWMRate(double rate);
public static native void setDigitalPWMDutyCycle(int pwmGenerator, double dutyCycle);
public static native void setDigitalPWMOutputChannel(int pwmGenerator, int channel);
}

View File

@@ -1,18 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2016-2018 FIRST. 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.hal;
public class DigitalGlitchFilterJNI extends JNIWrapper {
public static native void setFilterSelect(int digitalPortHandle, int filterIndex);
public static native int getFilterSelect(int digitalPortHandle);
public static native void setFilterPeriod(int filterIndex, int fpgaCycles);
public static native int getFilterPeriod(int filterIndex);
}

View File

@@ -1,62 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2016-2018 FIRST. 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.hal;
public class EncoderJNI extends JNIWrapper {
public static native int initializeEncoder(int digitalSourceHandleA, int analogTriggerTypeA,
int digitalSourceHandleB, int analogTriggerTypeB,
boolean reverseDirection, int encodingType);
public static native void freeEncoder(int encoderHandle);
public static native int getEncoder(int encoderHandle);
public static native int getEncoderRaw(int encoderHandle);
public static native int getEncodingScaleFactor(int encoderHandle);
public static native void resetEncoder(int encoderHandle);
public static native double getEncoderPeriod(int encoderHandle);
public static native void setEncoderMaxPeriod(int encoderHandle, double maxPeriod);
public static native boolean getEncoderStopped(int encoderHandle);
public static native boolean getEncoderDirection(int encoderHandle);
public static native double getEncoderDistance(int encoderHandle);
public static native double getEncoderRate(int encoderHandle);
public static native void setEncoderMinRate(int encoderHandle, double minRate);
public static native void setEncoderDistancePerPulse(int encoderHandle, double distancePerPulse);
public static native void setEncoderReverseDirection(int encoderHandle,
boolean reverseDirection);
public static native void setEncoderSamplesToAverage(int encoderHandle,
int samplesToAverage);
public static native int getEncoderSamplesToAverage(int encoderHandle);
public static native void setEncoderIndexSource(int encoderHandle, int digitalSourceHandle,
int analogTriggerType, int indexingType);
@SuppressWarnings("AbbreviationAsWordInName")
public static native int getEncoderFPGAIndex(int encoderHandle);
public static native int getEncoderEncodingScale(int encoderHandle);
public static native double getEncoderDecodingScaleFactor(int encoderHandle);
public static native double getEncoderDistancePerPulse(int encoderHandle);
public static native int getEncoderEncodingType(int encoderHandle);
}

View File

@@ -1,160 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2016-2018 FIRST. 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.hal;
/**
* JNI wrapper for library <b>FRC_NetworkCommunication</b><br>.
*/
@SuppressWarnings("MethodName")
public class FRCNetComm extends JNIWrapper {
/**
* Module type from LoadOut.h
*/
@SuppressWarnings("TypeName")
public interface tModuleType {
int kModuleType_Unknown = 0x00;
int kModuleType_Analog = 0x01;
int kModuleType_Digital = 0x02;
int kModuleType_Solenoid = 0x03;
}
/**
* Target class from LoadOut.h
*/
@SuppressWarnings("TypeName")
public interface tTargetClass {
int kTargetClass_Unknown = 0x00;
int kTargetClass_FRC1 = 0x10;
int kTargetClass_FRC2 = 0x20;
int kTargetClass_FRC3 = 0x30;
int kTargetClass_RoboRIO = 0x40;
int kTargetClass_FRC2_Analog = kTargetClass_FRC2 | tModuleType.kModuleType_Analog;
int kTargetClass_FRC2_Digital = kTargetClass_FRC2 | tModuleType.kModuleType_Digital;
int kTargetClass_FRC2_Solenoid = kTargetClass_FRC2 | tModuleType.kModuleType_Solenoid;
int kTargetClass_FamilyMask = 0xF0;
int kTargetClass_ModuleMask = 0x0F;
}
/**
* Resource type from UsageReporting.h
*/
@SuppressWarnings("TypeName")
public interface tResourceType {
int kResourceType_Controller = 0;
int kResourceType_Module = 1;
int kResourceType_Language = 2;
int kResourceType_CANPlugin = 3;
int kResourceType_Accelerometer = 4;
int kResourceType_ADXL345 = 5;
int kResourceType_AnalogChannel = 6;
int kResourceType_AnalogTrigger = 7;
int kResourceType_AnalogTriggerOutput = 8;
int kResourceType_CANJaguar = 9;
int kResourceType_Compressor = 10;
int kResourceType_Counter = 11;
int kResourceType_Dashboard = 12;
int kResourceType_DigitalInput = 13;
int kResourceType_DigitalOutput = 14;
int kResourceType_DriverStationCIO = 15;
int kResourceType_DriverStationEIO = 16;
int kResourceType_DriverStationLCD = 17;
int kResourceType_Encoder = 18;
int kResourceType_GearTooth = 19;
int kResourceType_Gyro = 20;
int kResourceType_I2C = 21;
int kResourceType_Framework = 22;
int kResourceType_Jaguar = 23;
int kResourceType_Joystick = 24;
int kResourceType_Kinect = 25;
int kResourceType_KinectStick = 26;
int kResourceType_PIDController = 27;
int kResourceType_Preferences = 28;
int kResourceType_PWM = 29;
int kResourceType_Relay = 30;
int kResourceType_RobotDrive = 31;
int kResourceType_SerialPort = 32;
int kResourceType_Servo = 33;
int kResourceType_Solenoid = 34;
int kResourceType_SPI = 35;
int kResourceType_Task = 36;
int kResourceType_Ultrasonic = 37;
int kResourceType_Victor = 38;
int kResourceType_Button = 39;
int kResourceType_Command = 40;
int kResourceType_AxisCamera = 41;
int kResourceType_PCVideoServer = 42;
int kResourceType_SmartDashboard = 43;
int kResourceType_Talon = 44;
int kResourceType_HiTechnicColorSensor = 45;
int kResourceType_HiTechnicAccel = 46;
int kResourceType_HiTechnicCompass = 47;
int kResourceType_SRF08 = 48;
int kResourceType_AnalogOutput = 49;
int kResourceType_VictorSP = 50;
int kResourceType_PWMTalonSRX = 51;
int kResourceType_CANTalonSRX = 52;
int kResourceType_ADXL362 = 53;
int kResourceType_ADXRS450 = 54;
int kResourceType_RevSPARK = 55;
int kResourceType_MindsensorsSD540 = 56;
int kResourceType_DigitalFilter = 57;
int kResourceType_ADIS16448 = 58;
int kResourceType_PDP = 59;
int kResourceType_PCM = 60;
int kResourceType_PigeonIMU = 61;
int kResourceType_NidecBrushless = 62;
}
/**
* Instances from UsageReporting.h
*/
@SuppressWarnings("TypeName")
public interface tInstances {
int kLanguage_LabVIEW = 1;
int kLanguage_CPlusPlus = 2;
int kLanguage_Java = 3;
int kLanguage_Python = 4;
int kCANPlugin_BlackJagBridge = 1;
int kCANPlugin_2CAN = 2;
int kFramework_Iterative = 1;
int kFramework_Simple = 2;
int kFramework_CommandControl = 3;
int kRobotDrive_ArcadeStandard = 1;
int kRobotDrive_ArcadeButtonSpin = 2;
int kRobotDrive_ArcadeRatioCurve = 3;
int kRobotDrive_Tank = 4;
int kRobotDrive_MecanumPolar = 5;
int kRobotDrive_MecanumCartesian = 6;
int kDriverStationCIO_Analog = 1;
int kDriverStationCIO_DigitalIn = 2;
int kDriverStationCIO_DigitalOut = 3;
int kDriverStationEIO_Acceleration = 1;
int kDriverStationEIO_AnalogIn = 2;
int kDriverStationEIO_AnalogOut = 3;
int kDriverStationEIO_Button = 4;
int kDriverStationEIO_LED = 5;
int kDriverStationEIO_DigitalIn = 6;
int kDriverStationEIO_DigitalOut = 7;
int kDriverStationEIO_FixedDigitalOut = 8;
int kDriverStationEIO_PWM = 9;
int kDriverStationEIO_Encoder = 10;
int kDriverStationEIO_TouchSlider = 11;
int kADXL345_SPI = 1;
int kADXL345_I2C = 2;
int kCommand_Scheduler = 1;
int kSmartDashboard_Instance = 1;
}
}

View File

@@ -1,126 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2016-2018 FIRST. 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.hal;
import java.nio.ByteBuffer;
/**
* JNI Wrapper for HAL<br>.
*/
@SuppressWarnings({"AbbreviationAsWordInName", "MethodName"})
public class HAL extends JNIWrapper {
public static native void waitForDSData();
public static native boolean initialize(int timeout, int mode);
public static native void observeUserProgramStarting();
public static native void observeUserProgramDisabled();
public static native void observeUserProgramAutonomous();
public static native void observeUserProgramTeleop();
public static native void observeUserProgramTest();
public static void report(int resource, int instanceNumber) {
report(resource, instanceNumber, 0, "");
}
public static void report(int resource, int instanceNumber, int context) {
report(resource, instanceNumber, context, "");
}
/**
* Report the usage of a resource of interest. <br>
*
* <p>Original signature: <code>uint32_t report(tResourceType, uint8_t, uint8_t, const
* char*)</code>
*
* @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.
*/
public static native int report(int resource, int instanceNumber, int context, String feature);
public static native int nativeGetControlWord();
@SuppressWarnings("JavadocMethod")
public static void getControlWord(ControlWord controlWord) {
int word = nativeGetControlWord();
controlWord.update((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 nativeGetAllianceStation();
@SuppressWarnings("JavadocMethod")
public static AllianceStationID getAllianceStation() {
switch (nativeGetAllianceStation()) {
case 0:
return AllianceStationID.Red1;
case 1:
return AllianceStationID.Red2;
case 2:
return AllianceStationID.Red3;
case 3:
return AllianceStationID.Blue1;
case 4:
return AllianceStationID.Blue2;
case 5:
return AllianceStationID.Blue3;
default:
return null;
}
}
@SuppressWarnings("JavadocMethod")
public static native boolean isNewControlData();
@SuppressWarnings("JavadocMethod")
public static native void releaseDSMutex();
@SuppressWarnings("JavadocMethod")
public static native boolean waitForDSDataTimeout(double timeout);
public static int kMaxJoystickAxes = 12;
public static int kMaxJoystickPOVs = 12;
public static native short getJoystickAxes(byte joystickNum, float[] axesArray);
public static native short getJoystickPOVs(byte joystickNum, short[] povsArray);
public static native int getJoystickButtons(byte joystickNum, ByteBuffer count);
public static native int setJoystickOutputs(byte joystickNum, int outputs, short leftRumble,
short rightRumble);
public static native int getJoystickIsXbox(byte joystickNum);
public static native int getJoystickType(byte joystickNum);
public static native String getJoystickName(byte joystickNum);
public static native int getJoystickAxisType(byte joystickNum, byte axis);
public static native double getMatchTime();
public static native boolean getSystemActive();
public static native boolean getBrownedOut();
public static native int getMatchInfo(MatchInfoData info);
public static native int sendError(boolean isError, int errorCode, boolean isLVCode,
String details, String location, String callStack,
boolean printMsg);
}

View File

@@ -1,40 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2016-2018 FIRST. 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.hal;
@SuppressWarnings("AbbreviationAsWordInName")
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 native short getFPGAVersion();
public static native int getFPGARevision();
public static native long getFPGATime();
public static native int getHALRuntimeType();
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

@@ -1,33 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2016-2018 FIRST. 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.hal;
import java.nio.ByteBuffer;
@SuppressWarnings("AbbreviationAsWordInName")
public class I2CJNI extends JNIWrapper {
public static native void i2CInitialize(int port);
public static native int i2CTransaction(int port, byte address, ByteBuffer dataToSend,
byte sendSize, ByteBuffer dataReceived, byte receiveSize);
public static native int i2CTransactionB(int port, byte address, byte[] dataToSend,
byte sendSize, byte[] dataReceived, byte receiveSize);
public static native int i2CWrite(int port, byte address, ByteBuffer dataToSend, byte sendSize);
public static native int i2CWriteB(int port, byte address, byte[] dataToSend, byte sendSize);
public static native int i2CRead(int port, byte address, ByteBuffer dataReceived,
byte receiveSize);
public static native int i2CReadB(int port, byte address, byte[] dataReceived,
byte receiveSize);
public static native void i2CClose(int port);
}

View File

@@ -1,41 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2016-2018 FIRST. 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.hal;
public class InterruptJNI extends JNIWrapper {
public static final int HalInvalidHandle = 0;
public interface InterruptJNIHandlerFunction {
void apply(int interruptAssertedMask, Object param);
}
public static native int initializeInterrupts(boolean watcher);
public static native void cleanInterrupts(int interruptHandle);
public static native int waitForInterrupt(int interruptHandle, double timeout,
boolean ignorePrevious);
public static native void enableInterrupts(int interruptHandle);
public static native void disableInterrupts(int interruptHandle);
public static native double readInterruptRisingTimestamp(int interruptHandle);
public static native double readInterruptFallingTimestamp(int interruptHandle);
public static native void requestInterrupts(int interruptHandle, int digitalSourceHandle,
int analogTriggerType);
public static native void attachInterruptHandler(int interruptHandle,
InterruptJNIHandlerFunction handler,
Object param);
public static native void setInterruptUpSourceEdge(int interruptHandle, boolean risingEdge,
boolean fallingEdge);
}

View File

@@ -1,72 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2016-2018 FIRST. 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.hal;
import edu.wpi.first.wpiutil.RuntimeDetector;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Base class for all JNI wrappers.
*/
public class JNIWrapper {
static boolean libraryLoaded = false;
static File jniLibrary = null;
static {
if (!libraryLoaded) {
String jniFileName = "wpilibJNI";
try {
System.loadLibrary(jniFileName);
} catch (UnsatisfiedLinkError ule) {
try {
String resname = RuntimeDetector.getLibraryResource(jniFileName);
InputStream is = JNIWrapper.class.getResourceAsStream(resname);
if (is != null) {
// create temporary file
if (System.getProperty("os.name").startsWith("Windows")) {
jniLibrary = File.createTempFile(jniFileName, ".dll");
} else if (System.getProperty("os.name").startsWith("Mac")) {
jniLibrary = File.createTempFile(jniFileName, ".dylib");
} else {
jniLibrary = File.createTempFile(jniFileName, ".so");
}
// flag for delete on exit
jniLibrary.deleteOnExit();
OutputStream os = new FileOutputStream(jniLibrary);
byte[] buffer = new byte[1024];
int readBytes;
try {
while ((readBytes = is.read(buffer)) != -1) {
os.write(buffer, 0, readBytes);
}
} finally {
os.close();
is.close();
}
System.load(jniLibrary.getAbsolutePath());
} else {
System.loadLibrary(jniFileName);
}
} catch (IOException ex) {
ex.printStackTrace();
System.exit(1);
}
}
libraryLoaded = true;
}
}
public static native int getPortWithModule(byte module, byte channel);
public static native int getPort(byte channel);
}

View File

@@ -1,56 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2017-2018 FIRST. 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.hal;
/**
* Structure for holding the match info data request.
*/
public class MatchInfoData {
/**
* Stores the event name.
*/
@SuppressWarnings("MemberName")
public String eventName = "";
/**
* Stores the game specific message.
*/
@SuppressWarnings("MemberName")
public String gameSpecificMessage = "";
/**
* Stores the match number.
*/
@SuppressWarnings("MemberName")
public int matchNumber;
/**
* Stores the replay number.
*/
@SuppressWarnings("MemberName")
public int replayNumber;
/**
* Stores the match type.
*/
@SuppressWarnings("MemberName")
public int matchType;
/**
* Called from JNI to set the structure data.
*/
@SuppressWarnings("JavadocMethod")
public void setData(String eventName, String gameSpecificMessage,
int matchNumber, int replayNumber, int matchType) {
this.eventName = eventName;
this.gameSpecificMessage = gameSpecificMessage;
this.matchNumber = matchNumber;
this.replayNumber = replayNumber;
this.matchType = matchType;
}
}

View File

@@ -1,49 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2016-2018 FIRST. 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.hal;
/**
* The NotifierJNI class directly wraps the C++ HAL Notifier.
*
* <p>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.
*/
public static native int initializeNotifier();
/**
* Wakes up the waiter with time=0. Note: after this function is called, all
* calls to waitForNotifierAlarm() will immediately start returning 0.
*/
public static native void stopNotifier(int notifierHandle);
/**
* Deletes the notifier object when we are done with it.
*/
public static native void cleanNotifier(int notifierHandle);
/**
* Sets the notifier to wakeup the waiter in another triggerTime microseconds.
*/
public static native void updateNotifierAlarm(int notifierHandle, long triggerTime);
/**
* Cancels any pending wakeups set by updateNotifierAlarm(). Does NOT wake
* up any waiters.
*/
public static native void cancelNotifierAlarm(int notifierHandle);
/**
* Block until woken up by an alarm (or stop).
* @return Time when woken up.
*/
public static native long waitForNotifierAlarm(int notifierHandle);
}

View File

@@ -1,46 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2016-2018 FIRST. 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.hal;
public class OSSerialPortJNI 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, double 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 serialGetBytesReceived(byte port);
public static native int serialRead(byte port, byte[] buffer, int count);
public static native int serialWrite(byte port, byte[] 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

@@ -1,33 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2016-2018 FIRST. 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.hal;
@SuppressWarnings("AbbreviationAsWordInName")
public class PDPJNI extends JNIWrapper {
public static native void initializePDP(int module);
public static native boolean checkPDPModule(int module);
public static native boolean checkPDPChannel(int channel);
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

@@ -1,51 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2016-2018 FIRST. 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.hal;
import edu.wpi.first.wpilibj.PWMConfigDataResult;
@SuppressWarnings("AbbreviationAsWordInName")
public class PWMJNI extends DIOJNI {
public static native int initializePWMPort(int halPortHandle);
public static native boolean checkPWMChannel(int channel);
public static native void freePWMPort(int pwmPortHandle);
public static native void setPWMConfigRaw(int pwmPortHandle, int maxPwm,
int deadbandMaxPwm, int centerPwm,
int deadbandMinPwm, int minPwm);
public static native void setPWMConfig(int pwmPortHandle, double maxPwm,
double deadbandMaxPwm, double centerPwm,
double deadbandMinPwm, double minPwm);
public static native PWMConfigDataResult getPWMConfigRaw(int pwmPortHandle);
public static native void setPWMEliminateDeadband(int pwmPortHandle, boolean eliminateDeadband);
public static native boolean getPWMEliminateDeadband(int pwmPortHandle);
public static native void setPWMRaw(int pwmPortHandle, short value);
public static native void setPWMSpeed(int pwmPortHandle, double speed);
public static native void setPWMPosition(int pwmPortHandle, double position);
public static native short getPWMRaw(int pwmPortHandle);
public static native double getPWMSpeed(int pwmPortHandle);
public static native double getPWMPosition(int pwmPortHandle);
public static native void setPWMDisabled(int pwmPortHandle);
public static native void latchPWMZero(int pwmPortHandle);
public static native void setPWMPeriodScale(int pwmPortHandle, int squelchMask);
}

View File

@@ -1,46 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2016-2018 FIRST. 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.hal;
public class PortsJNI extends JNIWrapper {
public static native int getNumAccumulators();
public static native int getNumAnalogTriggers();
public static native int getNumAnalogInputs();
public static native int getNumAnalogOutputs();
public static native int getNumCounters();
public static native int getNumDigitalHeaders();
public static native int getNumPWMHeaders();
public static native int getNumDigitalChannels();
public static native int getNumPWMChannels();
public static native int getNumDigitalPWMOutputs();
public static native int getNumEncoders();
public static native int getNumInterrupts();
public static native int getNumRelayChannels();
public static native int getNumRelayHeaders();
public static native int getNumPCMModules();
public static native int getNumSolenoidChannels();
public static native int getNumPDPModules();
public static native int getNumPDPChannels();
}

View File

@@ -1,38 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2016-2018 FIRST. 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.hal;
public class PowerJNI extends JNIWrapper {
public static native double getVinVoltage();
public static native double getVinCurrent();
public static native double getUserVoltage6V();
public static native double getUserCurrent6V();
public static native boolean getUserActive6V();
public static native int getUserCurrentFaults6V();
public static native double getUserVoltage5V();
public static native double getUserCurrent5V();
public static native boolean getUserActive5V();
public static native int getUserCurrentFaults5V();
public static native double getUserVoltage3V3();
public static native double getUserCurrent3V3();
public static native boolean getUserActive3V3();
public static native int getUserCurrentFaults3V3();
}

View File

@@ -1,20 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2016-2018 FIRST. 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.hal;
public class RelayJNI extends DIOJNI {
public static native int initializeRelayPort(int halPortHandle, boolean forward);
public static native void freeRelayPort(int relayPortHandle);
public static native boolean checkRelayChannel(int channel);
public static native void setRelay(int relayPortHandle, boolean on);
public static native boolean getRelay(int relayPortHandle);
}

View File

@@ -1,64 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2016-2018 FIRST. 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.hal;
import java.nio.ByteBuffer;
@SuppressWarnings("AbbreviationAsWordInName")
public class SPIJNI extends JNIWrapper {
public static native void spiInitialize(int port);
public static native int spiTransaction(int port, ByteBuffer dataToSend,
ByteBuffer dataReceived, byte size);
public static native int spiTransactionB(int port, byte[] dataToSend,
byte[] dataReceived, byte size);
public static native int spiWrite(int port, ByteBuffer dataToSend, byte sendSize);
public static native int spiWriteB(int port, byte[] dataToSend, byte sendSize);
public static native int spiRead(int port, boolean initiate, ByteBuffer dataReceived, byte size);
public static native int spiReadB(int port, boolean initiate, byte[] dataReceived, byte size);
public static native void spiClose(int port);
public static native void spiSetSpeed(int port, int speed);
public static native void spiSetOpts(int port, int msbFirst, int sampleOnTrailing,
int clkIdleHigh);
public static native void spiSetChipSelectActiveHigh(int port);
public static native void spiSetChipSelectActiveLow(int port);
public static native void spiInitAuto(int port, int bufferSize);
public static native void spiFreeAuto(int port);
public static native void spiStartAutoRate(int port, double period);
public static native void spiStartAutoTrigger(int port, int digitalSourceHandle,
int analogTriggerType, boolean triggerRising,
boolean triggerFalling);
public static native void spiStopAuto(int port);
public static native void spiSetAutoTransmitData(int port, byte[] dataToSend, int zeroSize);
public static native void spiForceAutoRead(int port);
public static native int spiReadAutoReceivedData(int port, ByteBuffer buffer, int numToRead,
double timeout);
public static native int spiReadAutoReceivedData(int port, byte[] buffer, int numToRead,
double timeout);
public static native int spiGetAutoDroppedCount(int port);
}

View File

@@ -1,48 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2016-2018 FIRST. 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.hal;
public class SerialPortJNI extends JNIWrapper {
public static native void serialInitializePort(byte port);
public static native void serialInitializePortDirect(byte port, String portName);
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, double 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 serialGetBytesReceived(byte port);
public static native int serialRead(byte port, byte[] buffer, int count);
public static native int serialWrite(byte port, byte[] 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

@@ -1,36 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2016-2018 FIRST. 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.hal;
public class SolenoidJNI extends JNIWrapper {
public static native int initializeSolenoidPort(int halPortHandle);
public static native boolean checkSolenoidModule(int module);
public static native boolean checkSolenoidChannel(int channel);
public static native void freeSolenoidPort(int portHandle);
public static native void setSolenoid(int portHandle, boolean on);
public static native boolean getSolenoid(int portHandle);
public static native int getAllSolenoids(int module);
public static native int getPCMSolenoidBlackList(int module);
public static native boolean getPCMSolenoidVoltageStickyFault(int module);
public static native boolean getPCMSolenoidVoltageFault(int module);
public static native void clearAllPCMStickyFaults(int module);
public static native void setOneShotDuration(int portHandle, long durationMS);
public static native void fireOneShot(int portHandle);
}

View File

@@ -1,16 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2016-2018 FIRST. 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.hal;
public class ThreadsJNI extends JNIWrapper {
public static native int getCurrentThreadPriority();
public static native boolean getCurrentThreadIsRealTime();
public static native boolean setCurrentThreadPriority(boolean realTime, int priority);
}

View File

@@ -1,25 +1,25 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>WPI Robotics library</title>
<meta http-equiv="Content-Type" content="text/html; charset=MacRoman">
</head>
<body>
The WPI Robotics library (WPILibJ) is a set of Java classes that interfaces to the hardware in the
FRC control system and your robot. There are classes to handle sensors, motors, the driver
station, and a number of other utility functions like timing and field management.
The library is designed to:
<ul>
<li>Deal with all the low level interfacing to these components so you can concentrate on
solving this year's "robot problem". This is a philosophical decision to let you focus
on the higher-level design of your robot rather than deal with the details of the
processor and the operating system.
</li>
<li>Understand everything at all levels by making the full source code of the library
available. You can study (and modify) the algorithms used by the gyro class for
oversampling and integration of the input signal or just ask the class for the current
robot heading. You can work at any level.
</li>
</ul>
</body>
</html>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>WPI Robotics library</title>
<meta http-equiv="Content-Type" content="text/html; charset=MacRoman">
</head>
<body>
The WPI Robotics library (WPILibJ) is a set of Java classes that interfaces to the hardware in the
FRC control system and your robot. There are classes to handle sensors, motors, the driver
station, and a number of other utility functions like timing and field management.
The library is designed to:
<ul>
<li>Deal with all the low level interfacing to these components so you can concentrate on
solving this year's "robot problem". This is a philosophical decision to let you focus
on the higher-level design of your robot rather than deal with the details of the
processor and the operating system.
</li>
<li>Understand everything at all levels by making the full source code of the library
available. You can study (and modify) the algorithms used by the gyro class for
oversampling and integration of the input signal or just ask the class for the current
robot heading. You can work at any level.
</li>
</ul>
</body>
</html>

View File

@@ -1,22 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2008-2018 FIRST. 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.util;
/**
* Exception indicating that the resource is already allocated.
*/
public class AllocationException extends RuntimeException {
/**
* Create a new AllocationException.
*
* @param msg the message to attach to the exception
*/
public AllocationException(String msg) {
super(msg);
}
}

View File

@@ -1,36 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2008-2018 FIRST. 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.util;
/**
* Thrown if there is an error caused by a basic system or setting not being properly initialized
* before being used.
*/
public class BaseSystemNotInitializedException extends RuntimeException {
/**
* Create a new BaseSystemNotInitializedException.
*
* @param message the message to attach to the exception
*/
public BaseSystemNotInitializedException(String message) {
super(message);
}
/**
* Create a new BaseSystemNotInitializedException using the offending class that was not set and
* the class that was affected.
*
* @param offender The class or interface that was not properly initialized.
* @param affected The class that was was affected by this missing initialization.
*/
public BaseSystemNotInitializedException(Class<?> offender, Class<?> affected) {
super("The " + offender.getSimpleName() + " for the " + affected.getSimpleName()
+ " was never set.");
}
}

View File

@@ -1,50 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2008-2018 FIRST. 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.util;
/**
* This exception represents an error in which a lower limit was set as higher than an upper limit.
*/
public class BoundaryException extends RuntimeException {
/**
* Create a new exception with the given message.
*
* @param message the message to attach to the exception
*/
public BoundaryException(String message) {
super(message);
}
/**
* Make sure that the given value is between the upper and lower bounds, and throw an exception if
* they are not.
*
* @param value The value to check.
* @param lower The minimum acceptable value.
* @param upper The maximum acceptable value.
*/
public static void assertWithinBounds(double value, double lower, double upper) {
if (value < lower || value > upper) {
throw new BoundaryException("Value must be between " + lower + " and " + upper + ", " + value
+ " given");
}
}
/**
* Returns the message for a boundary exception. Used to keep the message consistent across all
* boundary exceptions.
*
* @param value The given value
* @param lower The lower limit
* @param upper The upper limit
* @return the message for a boundary exception
*/
public static String getMessage(double value, double lower, double upper) {
return "Value must be between " + lower + " and " + upper + ", " + value + " given";
}
}

View File

@@ -1,23 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2008-2018 FIRST. 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.util;
/**
* Exception indicating that the resource is already allocated This is meant to be thrown by the
* resource class.
*/
public class CheckedAllocationException extends Exception {
/**
* Create a new CheckedAllocationException.
*
* @param msg the message to attach to the exception
*/
public CheckedAllocationException(String msg) {
super(msg);
}
}

View File

@@ -1,22 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2008-2018 FIRST. 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.util;
/**
* Exception indicating that an error has occured with a HAL Handle.
*/
public class HalHandleException extends RuntimeException {
/**
* Create a new HalHandleException.
*
* @param msg the message to attach to the exception
*/
public HalHandleException(String msg) {
super(msg);
}
}

View File

@@ -1,60 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2008-2018 FIRST. 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.util;
/**
* Exception for bad status codes from the chip object.
*/
public final class UncleanStatusException extends IllegalStateException {
private final int m_statusCode;
/**
* Create a new UncleanStatusException.
*
* @param status the status code that caused the exception
* @param message A message describing the exception
*/
public UncleanStatusException(int status, String message) {
super(message);
m_statusCode = status;
}
/**
* Create a new UncleanStatusException.
*
* @param status the status code that caused the exception
*/
public UncleanStatusException(int status) {
this(status, "Status code was non-zero");
}
/**
* Create a new UncleanStatusException.
*
* @param message a message describing the exception
*/
public UncleanStatusException(String message) {
this(-1, message);
}
/**
* Create a new UncleanStatusException.
*/
public UncleanStatusException() {
this(-1, "Status code was non-zero");
}
/**
* Create a new UncleanStatusException.
*
* @return the status code that caused the exception
*/
public int getStatus() {
return m_statusCode;
}
}

View File

@@ -1,27 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2016-2018 FIRST. 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.vision;
import org.opencv.core.Mat;
/**
* A vision pipeline is responsible for running a group of
* OpenCV algorithms to extract data from an image.
*
* @see VisionRunner
* @see VisionThread
*/
public interface VisionPipeline {
/**
* Processes the image input and sets the result objects.
* Implementations should make these objects accessible.
*/
void process(Mat image);
}

View File

@@ -1,121 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2016-2018 FIRST. 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.vision;
import edu.wpi.cscore.CvSink;
import edu.wpi.cscore.VideoSource;
import edu.wpi.first.wpilibj.DriverStation;
import edu.wpi.first.wpilibj.RobotBase;
import org.opencv.core.Mat;
/**
* A vision runner is a convenient wrapper object to make it easy to run vision pipelines
* from robot code. The easiest way to use this is to run it in a {@link VisionThread}
* and use the listener to take snapshots of the pipeline's outputs.
*
* @see VisionPipeline
* @see VisionThread
* @see edu.wpi.first.wpilibj.vision
*/
public class VisionRunner<P extends VisionPipeline> {
private final CvSink m_cvSink = new CvSink("VisionRunner CvSink");
private final P m_pipeline;
private final Mat m_image = new Mat();
private final Listener<? super P> m_listener;
private volatile boolean m_enabled = true;
/**
* Listener interface for a callback that should run after a pipeline has processed its input.
*
* @param <P> the type of the pipeline this listener is for
*/
@FunctionalInterface
public interface Listener<P extends VisionPipeline> {
/**
* Called when the pipeline has run. This shouldn't take much time to run because it will delay
* later calls to the pipeline's {@link VisionPipeline#process process} method. Copying the
* outputs and code that uses the copies should be <i>synchronized</i> on the same mutex to
* prevent multiple threads from reading and writing to the same memory at the same time.
*
* @param pipeline the vision pipeline that ran
*/
void copyPipelineOutputs(P pipeline);
}
/**
* Creates a new vision runner. It will take images from the {@code videoSource}, send them to
* the {@code pipeline}, and call the {@code listener} when the pipeline has finished to alert
* user code when it is safe to access the pipeline's outputs.
*
* @param videoSource the video source to use to supply images for the pipeline
* @param pipeline the vision pipeline to run
* @param listener a function to call after the pipeline has finished running
*/
public VisionRunner(VideoSource videoSource, P pipeline, Listener<? super P> listener) {
this.m_pipeline = pipeline;
this.m_listener = listener;
m_cvSink.setSource(videoSource);
}
/**
* Runs the pipeline one time, giving it the next image from the video source specified
* in the constructor. This will block until the source either has an image or throws an error.
* If the source successfully supplied a frame, the pipeline's image input will be set,
* the pipeline will run, and the listener specified in the constructor will be called to notify
* it that the pipeline ran.
*
* <p>This method is exposed to allow teams to add additional functionality or have their own
* ways to run the pipeline. Most teams, however, should just use {@link #runForever} in its own
* thread using a {@link VisionThread}.</p>
*/
public void runOnce() {
if (Thread.currentThread().getId() == RobotBase.MAIN_THREAD_ID) {
throw new IllegalStateException(
"VisionRunner.runOnce() cannot be called from the main robot thread");
}
long frameTime = m_cvSink.grabFrame(m_image);
if (frameTime == 0) {
// There was an error, report it
String error = m_cvSink.getError();
DriverStation.reportError(error, true);
} else {
// No errors, process the image
m_pipeline.process(m_image);
m_listener.copyPipelineOutputs(m_pipeline);
}
}
/**
* A convenience method that calls {@link #runOnce()} in an infinite loop. This must
* be run in a dedicated thread, and cannot be used in the main robot thread because
* it will freeze the robot program.
*
* <p><strong>Do not call this method directly from the main thread.</strong></p>
*
* @throws IllegalStateException if this is called from the main robot thread
* @see VisionThread
*/
public void runForever() {
if (Thread.currentThread().getId() == RobotBase.MAIN_THREAD_ID) {
throw new IllegalStateException(
"VisionRunner.runForever() cannot be called from the main robot thread");
}
while (m_enabled && !Thread.interrupted()) {
runOnce();
}
}
/**
* Stop a RunForever() loop.
*/
public void stop() {
m_enabled = false;
}
}

View File

@@ -1,47 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2016-2018 FIRST. 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.vision;
import edu.wpi.cscore.VideoSource;
/**
* A vision thread is a special thread that runs a vision pipeline. It is a <i>daemon</i> thread;
* it does not prevent the program from exiting when all other non-daemon threads
* have finished running.
*
* @see VisionPipeline
* @see VisionRunner
* @see Thread#setDaemon(boolean)
*/
public class VisionThread extends Thread {
/**
* Creates a vision thread that continuously runs a {@link VisionPipeline}.
*
* @param visionRunner the runner for a vision pipeline
*/
public VisionThread(VisionRunner<?> visionRunner) {
super(visionRunner::runForever, "WPILib Vision Thread");
setDaemon(true);
}
/**
* Creates a new vision thread that continuously runs the given vision pipeline. This is
* equivalent to {@code new VisionThread(new VisionRunner<>(videoSource, pipeline, listener))}.
*
* @param videoSource the source for images the pipeline should process
* @param pipeline the pipeline to run
* @param listener the listener to copy outputs from the pipeline after it runs
* @param <P> the type of the pipeline
*/
public <P extends VisionPipeline> VisionThread(VideoSource videoSource,
P pipeline,
VisionRunner.Listener<? super P> listener) {
this(new VisionRunner<>(videoSource, pipeline, listener));
}
}

View File

@@ -1,88 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2016-2018 FIRST. 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. */
/*----------------------------------------------------------------------------*/
/**
* Classes in the {@code edu.wpi.first.wpilibj.vision} package are designed to
* simplify using OpenCV vision processing code from a robot program.
*
* <p>An example use case for grabbing a yellow tote from 2015 in autonomous:
* <br>
* <pre><code>
* public class Robot extends IterativeRobot
* implements VisionRunner.Listener&lt;MyFindTotePipeline&gt; {
*
* // A USB camera connected to the roboRIO.
* private {@link edu.wpi.cscore.VideoSource VideoSource} usbCamera;
*
* // A vision pipeline. This could be handwritten or generated by GRIP.
* // This has to implement {@link edu.wpi.first.wpilibj.vision.VisionPipeline}.
* // For this example, assume that it's perfect and will always see the tote.
* private MyFindTotePipeline findTotePipeline;
* private {@link edu.wpi.first.wpilibj.vision.VisionThread} findToteThread;
*
* // The object to synchronize on to make sure the vision thread doesn't
* // write to variables the main thread is using.
* private final Object visionLock = new Object();
*
* // The pipeline outputs we want
* private boolean pipelineRan = false; // lets us know when the pipeline has actually run
* private double angleToTote = 0;
* private double distanceToTote = 0;
*
* {@literal @}Override
* public void {@link edu.wpi.first.wpilibj.vision.VisionRunner.Listener#copyPipelineOutputs
* copyPipelineOutputs(MyFindTotePipeline pipeline)} {
* synchronized (visionLock) {
* // Take a snapshot of the pipeline's output because
* // it may have changed the next time this method is called!
* this.pipelineRan = true;
* this.angleToTote = pipeline.getAngleToTote();
* this.distanceToTote = pipeline.getDistanceToTote();
* }
* }
*
* {@literal @}Override
* public void robotInit() {
* usbCamera = CameraServer.getInstance().startAutomaticCapture(0);
* findTotePipeline = new MyFindTotePipeline();
* findToteThread = new VisionThread(usbCamera, findTotePipeline, this);
* }
*
* {@literal @}Override
* public void autonomousInit() {
* findToteThread.start();
* }
*
* {@literal @}Override
* public void autonomousPeriodic() {
* double angle;
* double distance;
* synchronized (visionLock) {
* if (!pipelineRan) {
* // Wait until the pipeline has run
* return;
* }
* // Copy the outputs to make sure they're all from the same run
* angle = this.angleToTote;
* distance = this.distanceToTote;
* }
* if (!aimedAtTote()) {
* turnToAngle(angle);
* } else if (!droveToTote()) {
* driveDistance(distance);
* } else if (!grabbedTote()) {
* grabTote();
* } else {
* // Tote was grabbed and we're done!
* return;
* }
* }
*
* }
* </code></pre>
*/
package edu.wpi.first.wpilibj.vision;