Update to 2018_v4 image and new build system. (#598)

* Revert "Force OpenCV to 3.1.0 (#602)"

This reverts commit 50ed55e8e2.

* Removes Simulation

* Removes old build system

* Removes old gtest

* Adds new gmock and gtest

* Updates to new ni-libraries

* removes MyRobot (to be replaced)

* moves files to new location

* Adds new sim backend and new test executables

* updates .styleguide and .gitignore

* Changes cpp WPILibVersion to a function

MSVC throws an AV with the old version.

* Disables USBCamera on all systems except for linux

* 2018 NI Libraries

* New build system
This commit is contained in:
Thad House
2017-08-18 21:35:53 -07:00
committed by Peter Johnson
parent 50ed55e8e2
commit e1195e8b9d
1024 changed files with 64481 additions and 61340 deletions

View File

@@ -0,0 +1,87 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <memory>
#include <string>
#include "I2C.h"
#include "LiveWindow/LiveWindowSendable.h"
#include "interfaces/Accelerometer.h"
namespace frc {
/**
* ADXL345 Accelerometer on I2C.
*
* This class allows access to a Analog Devices ADXL345 3-axis accelerometer on
* an I2C bus.
* This class assumes the default (not alternate) sensor address of 0x1D (7-bit
* address).
*/
class ADXL345_I2C : public Accelerometer, public LiveWindowSendable {
protected:
static const int kAddress = 0x1D;
static const int kPowerCtlRegister = 0x2D;
static const int kDataFormatRegister = 0x31;
static const int kDataRegister = 0x32;
static constexpr double kGsPerLSB = 0.00390625;
enum PowerCtlFields {
kPowerCtl_Link = 0x20,
kPowerCtl_AutoSleep = 0x10,
kPowerCtl_Measure = 0x08,
kPowerCtl_Sleep = 0x04
};
enum DataFormatFields {
kDataFormat_SelfTest = 0x80,
kDataFormat_SPI = 0x40,
kDataFormat_IntInvert = 0x20,
kDataFormat_FullRes = 0x08,
kDataFormat_Justify = 0x04
};
public:
enum Axes { kAxis_X = 0x00, kAxis_Y = 0x02, kAxis_Z = 0x04 };
struct AllAxes {
double XAxis;
double YAxis;
double ZAxis;
};
public:
explicit ADXL345_I2C(I2C::Port port, Range range = kRange_2G,
int deviceAddress = kAddress);
virtual ~ADXL345_I2C() = default;
ADXL345_I2C(const ADXL345_I2C&) = delete;
ADXL345_I2C& operator=(const ADXL345_I2C&) = delete;
// Accelerometer interface
void SetRange(Range range) override;
double GetX() override;
double GetY() override;
double GetZ() override;
virtual double GetAcceleration(Axes axis);
virtual AllAxes GetAccelerations();
std::string GetSmartDashboardType() const override;
void InitTable(std::shared_ptr<ITable> subtable) override;
void UpdateTable() override;
std::shared_ptr<ITable> GetTable() const override;
void StartLiveWindowMode() override {}
void StopLiveWindowMode() override {}
protected:
I2C m_i2c;
private:
std::shared_ptr<ITable> m_table;
};
} // namespace frc

View File

@@ -0,0 +1,89 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <memory>
#include <string>
#include "LiveWindow/LiveWindowSendable.h"
#include "SPI.h"
#include "SensorBase.h"
#include "interfaces/Accelerometer.h"
namespace frc {
class DigitalInput;
class DigitalOutput;
/**
* ADXL345 Accelerometer on SPI.
*
* This class allows access to an Analog Devices ADXL345 3-axis accelerometer
* via SPI.
* This class assumes the sensor is wired in 4-wire SPI mode.
*/
class ADXL345_SPI : public Accelerometer, public LiveWindowSendable {
protected:
static const int kPowerCtlRegister = 0x2D;
static const int kDataFormatRegister = 0x31;
static const int kDataRegister = 0x32;
static constexpr double kGsPerLSB = 0.00390625;
enum SPIAddressFields { kAddress_Read = 0x80, kAddress_MultiByte = 0x40 };
enum PowerCtlFields {
kPowerCtl_Link = 0x20,
kPowerCtl_AutoSleep = 0x10,
kPowerCtl_Measure = 0x08,
kPowerCtl_Sleep = 0x04
};
enum DataFormatFields {
kDataFormat_SelfTest = 0x80,
kDataFormat_SPI = 0x40,
kDataFormat_IntInvert = 0x20,
kDataFormat_FullRes = 0x08,
kDataFormat_Justify = 0x04
};
public:
enum Axes { kAxis_X = 0x00, kAxis_Y = 0x02, kAxis_Z = 0x04 };
struct AllAxes {
double XAxis;
double YAxis;
double ZAxis;
};
public:
explicit ADXL345_SPI(SPI::Port port, Range range = kRange_2G);
virtual ~ADXL345_SPI() = default;
ADXL345_SPI(const ADXL345_SPI&) = delete;
ADXL345_SPI& operator=(const ADXL345_SPI&) = delete;
// Accelerometer interface
void SetRange(Range range) override;
double GetX() override;
double GetY() override;
double GetZ() override;
virtual double GetAcceleration(Axes axis);
virtual AllAxes GetAccelerations();
std::string GetSmartDashboardType() const override;
void InitTable(std::shared_ptr<ITable> subtable) override;
void UpdateTable() override;
std::shared_ptr<ITable> GetTable() const override;
void StartLiveWindowMode() override {}
void StopLiveWindowMode() override {}
protected:
SPI m_spi;
private:
std::shared_ptr<ITable> m_table;
};
} // namespace frc

View File

@@ -0,0 +1,68 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <memory>
#include <string>
#include "LiveWindow/LiveWindowSendable.h"
#include "SPI.h"
#include "SensorBase.h"
#include "interfaces/Accelerometer.h"
namespace frc {
class DigitalInput;
class DigitalOutput;
/**
* ADXL362 SPI Accelerometer.
*
* This class allows access to an Analog Devices ADXL362 3-axis accelerometer.
*/
class ADXL362 : public Accelerometer, public LiveWindowSendable {
public:
enum Axes { kAxis_X = 0x00, kAxis_Y = 0x02, kAxis_Z = 0x04 };
struct AllAxes {
double XAxis;
double YAxis;
double ZAxis;
};
public:
explicit ADXL362(Range range = kRange_2G);
explicit ADXL362(SPI::Port port, Range range = kRange_2G);
virtual ~ADXL362() = default;
ADXL362(const ADXL362&) = delete;
ADXL362& operator=(const ADXL362&) = delete;
// Accelerometer interface
void SetRange(Range range) override;
double GetX() override;
double GetY() override;
double GetZ() override;
virtual double GetAcceleration(Axes axis);
virtual AllAxes GetAccelerations();
std::string GetSmartDashboardType() const override;
void InitTable(std::shared_ptr<ITable> subtable) override;
void UpdateTable() override;
std::shared_ptr<ITable> GetTable() const override;
void StartLiveWindowMode() override {}
void StopLiveWindowMode() override {}
private:
SPI m_spi;
double m_gsPerLSB = 0.001;
std::shared_ptr<ITable> m_table;
};
} // namespace frc

View File

@@ -0,0 +1,45 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2015-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <stdint.h>
#include "GyroBase.h"
#include "SPI.h"
namespace frc {
/**
* Use a rate gyro to return the robots heading relative to a starting position.
* The Gyro class tracks the robots heading based on the starting position. As
* the robot rotates the new heading is computed by integrating the rate of
* rotation returned by the sensor. When the class is instantiated, it does a
* short calibration routine where it samples the gyro while at rest to
* determine the default offset. This is subtracted from each sample to
* determine the heading.
*
* This class is for the digital ADXRS450 gyro sensor that connects via SPI.
*/
class ADXRS450_Gyro : public GyroBase {
public:
ADXRS450_Gyro();
explicit ADXRS450_Gyro(SPI::Port port);
virtual ~ADXRS450_Gyro() = default;
double GetAngle() const override;
double GetRate() const override;
void Reset() override;
void Calibrate() override;
private:
SPI m_spi;
uint16_t ReadRegister(int reg);
};
} // namespace frc

View File

@@ -0,0 +1,57 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <memory>
#include <string>
#include "AnalogInput.h"
#include "LiveWindow/LiveWindowSendable.h"
#include "PIDSource.h"
#include "SensorBase.h"
namespace frc {
/**
* Handle operation of an analog accelerometer.
* The accelerometer reads acceleration directly through the sensor. Many
* sensors have multiple axis and can be treated as multiple devices. Each is
* calibrated by finding the center value over a period of time.
*/
class AnalogAccelerometer : public SensorBase,
public PIDSource,
public LiveWindowSendable {
public:
explicit AnalogAccelerometer(int channel);
explicit AnalogAccelerometer(AnalogInput* channel);
explicit AnalogAccelerometer(std::shared_ptr<AnalogInput> channel);
virtual ~AnalogAccelerometer() = default;
double GetAcceleration() const;
void SetSensitivity(double sensitivity);
void SetZero(double zero);
double PIDGet() override;
void UpdateTable() override;
void StartLiveWindowMode() override;
void StopLiveWindowMode() override;
std::string GetSmartDashboardType() const override;
void InitTable(std::shared_ptr<ITable> subTable) override;
std::shared_ptr<ITable> GetTable() const override;
private:
void InitAccelerometer();
std::shared_ptr<AnalogInput> m_analogInput;
double m_voltsPerG = 1.0;
double m_zeroGVoltage = 2.5;
std::shared_ptr<ITable> m_table;
};
} // namespace frc

View File

@@ -0,0 +1,64 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <memory>
#include "GyroBase.h"
#include "HAL/Types.h"
namespace frc {
class AnalogInput;
/**
* Use a rate gyro to return the robots heading relative to a starting position.
* The Gyro class tracks the robots heading based on the starting position. As
* the robot rotates the new heading is computed by integrating the rate of
* rotation returned by the sensor. When the class is instantiated, it does a
* short calibration routine where it samples the gyro while at rest to
* determine the default offset. This is subtracted from each sample to
* determine the heading. This gyro class must be used with a channel that is
* assigned one of the Analog accumulators from the FPGA. See AnalogInput for
* the current accumulator assignments.
*
* This class is for gyro sensors that connect to an analog input.
*/
class AnalogGyro : public GyroBase {
public:
static const int kOversampleBits = 10;
static const int kAverageBits = 0;
static constexpr double kSamplesPerSecond = 50.0;
static constexpr double kCalibrationSampleTime = 5.0;
static constexpr double kDefaultVoltsPerDegreePerSecond = 0.007;
explicit AnalogGyro(int channel);
explicit AnalogGyro(AnalogInput* channel);
explicit AnalogGyro(std::shared_ptr<AnalogInput> channel);
AnalogGyro(int channel, int center, double offset);
AnalogGyro(std::shared_ptr<AnalogInput> channel, int center, double offset);
virtual ~AnalogGyro();
double GetAngle() const override;
double GetRate() const override;
virtual int GetCenter() const;
virtual double GetOffset() const;
void SetSensitivity(double voltsPerDegreePerSecond);
void SetDeadband(double volts);
void Reset() override;
virtual void InitGyro();
void Calibrate() override;
protected:
std::shared_ptr<AnalogInput> m_analog;
private:
HAL_GyroHandle m_gyroHandle = HAL_kInvalidHandle;
};
} // namespace frc

View File

@@ -0,0 +1,95 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <stdint.h>
#include <memory>
#include <string>
#include "HAL/Types.h"
#include "LiveWindow/LiveWindowSendable.h"
#include "PIDSource.h"
#include "SensorBase.h"
namespace frc {
/**
* Analog input class.
*
* Connected to each analog channel is an averaging and oversampling engine.
* This engine accumulates the specified ( by SetAverageBits() and
* SetOversampleBits() ) number of samples before returning a new value. This
* is not a sliding window average. The only difference between the oversampled
* samples and the averaged samples is that the oversampled samples are simply
* accumulated effectively increasing the resolution, while the averaged samples
* are divided by the number of samples to retain the resolution, but get more
* stable values.
*/
class AnalogInput : public SensorBase,
public PIDSource,
public LiveWindowSendable {
friend class AnalogTrigger;
friend class AnalogGyro;
public:
static const int kAccumulatorModuleNumber = 1;
static const int kAccumulatorNumChannels = 2;
static const int kAccumulatorChannels[kAccumulatorNumChannels];
explicit AnalogInput(int channel);
virtual ~AnalogInput();
int GetValue() const;
int GetAverageValue() const;
double GetVoltage() const;
double GetAverageVoltage() const;
int GetChannel() const;
void SetAverageBits(int bits);
int GetAverageBits() const;
void SetOversampleBits(int bits);
int GetOversampleBits() const;
int GetLSBWeight() const;
int GetOffset() const;
bool IsAccumulatorChannel() const;
void InitAccumulator();
void SetAccumulatorInitialValue(int64_t value);
void ResetAccumulator();
void SetAccumulatorCenter(int center);
void SetAccumulatorDeadband(int deadband);
int64_t GetAccumulatorValue() const;
int64_t GetAccumulatorCount() const;
void GetAccumulatorOutput(int64_t& value, int64_t& count) const;
static void SetSampleRate(double samplesPerSecond);
static double GetSampleRate();
double PIDGet() override;
void UpdateTable() override;
void StartLiveWindowMode() override;
void StopLiveWindowMode() override;
std::string GetSmartDashboardType() const override;
void InitTable(std::shared_ptr<ITable> subTable) override;
std::shared_ptr<ITable> GetTable() const override;
private:
int m_channel;
// TODO: Adjust HAL to avoid use of raw pointers.
HAL_AnalogInputHandle m_port;
int64_t m_accumulatorOffset;
std::shared_ptr<ITable> m_table;
};
} // namespace frc

View File

@@ -0,0 +1,45 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2014-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <memory>
#include <string>
#include "HAL/AnalogOutput.h"
#include "LiveWindow/LiveWindowSendable.h"
#include "SensorBase.h"
namespace frc {
/**
* MXP analog output class.
*/
class AnalogOutput : public SensorBase, public LiveWindowSendable {
public:
explicit AnalogOutput(int channel);
virtual ~AnalogOutput();
void SetVoltage(double voltage);
double GetVoltage() const;
int GetChannel();
void UpdateTable() override;
void StartLiveWindowMode() override;
void StopLiveWindowMode() override;
std::string GetSmartDashboardType() const override;
void InitTable(std::shared_ptr<ITable> subTable) override;
std::shared_ptr<ITable> GetTable() const override;
protected:
int m_channel;
HAL_AnalogOutputHandle m_port;
std::shared_ptr<ITable> m_table;
};
} // namespace frc

View File

@@ -0,0 +1,96 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <memory>
#include <string>
#include "AnalogInput.h"
#include "LiveWindow/LiveWindowSendable.h"
#include "interfaces/Potentiometer.h"
namespace frc {
/**
* Class for reading analog potentiometers. Analog potentiometers read
* in an analog voltage that corresponds to a position. The position is
* in whichever units you choose, by way of the scaling and offset
* constants passed to the constructor.
*/
class AnalogPotentiometer : public Potentiometer, public LiveWindowSendable {
public:
/**
* AnalogPotentiometer constructor.
*
* Use the fullRange and offset values so that the output produces
* meaningful values. I.E: you have a 270 degree potentiometer and
* you want the output to be degrees with the halfway point as 0
* degrees. The fullRange value is 270.0(degrees) and the offset is
* -135.0 since the halfway point after scaling is 135 degrees.
*
* This will calculate the result from the fullRange times the
* fraction of the supply voltage, plus the offset.
*
* @param channel The analog channel this potentiometer is plugged into.
* @param fullRange The scaling to multiply the voltage by to get a meaningful
* unit.
* @param offset The offset to add to the scaled value for controlling the
* zero value
*/
explicit AnalogPotentiometer(int channel, double fullRange = 1.0,
double offset = 0.0);
explicit AnalogPotentiometer(AnalogInput* input, double fullRange = 1.0,
double offset = 0.0);
explicit AnalogPotentiometer(std::shared_ptr<AnalogInput> input,
double fullRange = 1.0, double offset = 0.0);
virtual ~AnalogPotentiometer() = default;
/**
* Get the current reading of the potentiomer.
*
* @return The current position of the potentiometer.
*/
double Get() const override;
/**
* Implement the PIDSource interface.
*
* @return The current reading.
*/
double PIDGet() override;
/*
* Live Window code, only does anything if live window is activated.
*/
std::string GetSmartDashboardType() const override;
void InitTable(std::shared_ptr<ITable> subtable) override;
void UpdateTable() override;
std::shared_ptr<ITable> GetTable() const override;
/**
* AnalogPotentiometers don't have to do anything special when entering the
* LiveWindow.
*/
void StartLiveWindowMode() override {}
/**
* AnalogPotentiometers don't have to do anything special when exiting the
* LiveWindow.
*/
void StopLiveWindowMode() override {}
private:
std::shared_ptr<AnalogInput> m_analog_input;
double m_fullRange, m_offset;
std::shared_ptr<ITable> m_table;
};
} // namespace frc

View File

@@ -0,0 +1,45 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <memory>
#include "AnalogTriggerOutput.h"
#include "HAL/Types.h"
#include "SensorBase.h"
namespace frc {
class AnalogInput;
class AnalogTrigger : public SensorBase {
friend class AnalogTriggerOutput;
public:
explicit AnalogTrigger(int channel);
explicit AnalogTrigger(AnalogInput* channel);
virtual ~AnalogTrigger();
void SetLimitsVoltage(double lower, double upper);
void SetLimitsRaw(int lower, int upper);
void SetAveraged(bool useAveragedValue);
void SetFiltered(bool useFilteredValue);
int GetIndex() const;
bool GetInWindow();
bool GetTriggerState();
std::shared_ptr<AnalogTriggerOutput> CreateOutput(
AnalogTriggerType type) const;
private:
int m_index;
HAL_AnalogTriggerHandle m_trigger;
AnalogInput* m_analogInput = nullptr;
bool m_ownsAnalog = false;
};
} // namespace frc

View File

@@ -0,0 +1,73 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include "DigitalSource.h"
#include "HAL/AnalogTrigger.h"
namespace frc {
class AnalogTrigger;
/**
* Class to represent a specific output from an analog trigger.
*
* This class is used to get the current output value and also as a
* DigitalSource to provide routing of an output to digital subsystems on the
* FPGA such as Counter, Encoder, and Interrupt.
*
* The TriggerState output indicates the primary output value of the trigger.
* If the analog signal is less than the lower limit, the output is false. If
* the analog value is greater than the upper limit, then the output is true.
* If the analog value is in between, then the trigger output state maintains
* its most recent value.
*
* The InWindow output indicates whether or not the analog signal is inside the
* range defined by the limits.
*
* The RisingPulse and FallingPulse outputs detect an instantaneous transition
* from above the upper limit to below the lower limit, and vise versa. These
* pulses represent a rollover condition of a sensor and can be routed to an up
* / down counter or to interrupts. Because the outputs generate a pulse, they
* cannot be read directly. To help ensure that a rollover condition is not
* missed, there is an average rejection filter available that operates on the
* upper 8 bits of a 12 bit number and selects the nearest outlyer of 3 samples.
* This will reject a sample that is (due to averaging or sampling) errantly
* between the two limits. This filter will fail if more than one sample in a
* row is errantly in between the two limits. You may see this problem if
* attempting to use this feature with a mechanical rollover sensor, such as a
* 360 degree no-stop potentiometer without signal conditioning, because the
* rollover transition is not sharp / clean enough. Using the averaging engine
* may help with this, but rotational speeds of the sensor will then be limited.
*/
class AnalogTriggerOutput : public DigitalSource {
friend class AnalogTrigger;
public:
virtual ~AnalogTriggerOutput();
bool Get() const;
// DigitalSource interface
HAL_Handle GetPortHandleForRouting() const override;
AnalogTriggerType GetAnalogTriggerTypeForRouting() const override;
bool IsAnalogTrigger() const override;
int GetChannel() const override;
protected:
AnalogTriggerOutput(const AnalogTrigger& trigger,
AnalogTriggerType outputType);
private:
// Uses reference rather than smart pointer because a user can not construct
// an AnalogTriggerOutput themselves and because the AnalogTriggerOutput
// should always be in scope at the same time as an AnalogTrigger.
const AnalogTrigger& m_trigger;
AnalogTriggerType m_outputType;
};
} // namespace frc

View File

@@ -0,0 +1,19 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
namespace frc {
enum class AnalogTriggerType {
kInWindow = 0,
kState = 1,
kRisingPulse = 2,
kFallingPulse = 3
};
} // namespace frc

View File

@@ -0,0 +1,79 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include "HAL/cpp/make_unique.h"
// MSVC 2013 doesn't allow "= default" on move constructors, but since we are
// (currently) only actually using the move constructors in non-MSVC situations
// (ie, wpilibC++Devices), we can just ignore it in MSVC.
#if defined(_MSC_VER) && _MSC_VER < 1900
#define DEFAULT_MOVE_CONSTRUCTOR(ClassName)
#else
#define DEFAULT_MOVE_CONSTRUCTOR(ClassName) ClassName(ClassName&&) = default
#endif
#if defined(_MSC_VER) && _MSC_VER < 1900
#define constexpr const
#endif
#if (__cplusplus < 201103L) && !defined(_MSC_VER)
#define nullptr NULL
#endif
#if defined(_MSC_VER) && _MSC_VER < 1900
#define noexcept throw()
#endif
// Provide std::decay_t when using GCC < 4.9
#if defined(__GNUC__)
#if __GNUC__ == 4 && __GNUC_MINOR__ < 9
#include <type_traits>
namespace std {
template <class T>
using decay_t = typename decay<T>::type;
}
#endif
#endif
namespace frc {
// A struct to use as a deleter when a std::shared_ptr must wrap a raw pointer
// that is being deleted by someone else.
template <class T>
struct NullDeleter {
void operator()(T*) const noexcept {};
};
} // namespace frc
#include <atomic>
namespace frc {
// Use this for determining whether the default move constructor has been
// called on a containing object. This serves the purpose of allowing us to
// use the default move constructor of an object for moving all the data around
// while being able to use this to, for instance, chose not to de-allocate
// a PWM port in a destructor.
struct HasBeenMoved {
HasBeenMoved(HasBeenMoved&& other) {
other.moved = true;
moved = false;
}
HasBeenMoved() = default;
std::atomic<bool> moved{false};
operator bool() const { return moved; }
};
} // namespace frc
// For backwards compatibility
#ifndef NAMESPACED_WPILIB
using namespace frc; // NOLINT
#endif

View File

@@ -0,0 +1,48 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2014-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <memory>
#include <string>
#include "LiveWindow/LiveWindowSendable.h"
#include "SensorBase.h"
#include "interfaces/Accelerometer.h"
namespace frc {
/**
* Built-in accelerometer.
*
* This class allows access to the roboRIO's internal accelerometer.
*/
class BuiltInAccelerometer : public Accelerometer,
public SensorBase,
public LiveWindowSendable {
public:
explicit BuiltInAccelerometer(Range range = kRange_8G);
virtual ~BuiltInAccelerometer() = default;
// Accelerometer interface
void SetRange(Range range) override;
double GetX() override;
double GetY() override;
double GetZ() override;
std::string GetSmartDashboardType() const override;
void InitTable(std::shared_ptr<ITable> subtable) override;
void UpdateTable() override;
std::shared_ptr<ITable> GetTable() const override;
void StartLiveWindowMode() override {}
void StopLiveWindowMode() override {}
private:
std::shared_ptr<ITable> m_table;
};
} // namespace frc

View File

@@ -0,0 +1,36 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include "Buttons/Trigger.h"
#include "Commands/Command.h"
namespace frc {
/**
* This class provides an easy way to link commands to OI inputs.
*
* It is very easy to link a button to a command. For instance, you could
* link the trigger button of a joystick to a "score" command.
*
* This class represents a subclass of Trigger that is specifically aimed at
* buttons on an operator interface as a common use case of the more generalized
* Trigger objects. This is a simple wrapper around Trigger with the method
* names
* renamed to fit the Button object use.
*/
class Button : public Trigger {
public:
virtual void WhenPressed(Command* command);
virtual void WhileHeld(Command* command);
virtual void WhenReleased(Command* command);
virtual void CancelWhenPressed(Command* command);
virtual void ToggleWhenPressed(Command* command);
};
} // namespace frc

View File

@@ -0,0 +1,28 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
namespace frc {
class Trigger;
class Command;
class ButtonScheduler {
public:
ButtonScheduler(bool last, Trigger* button, Command* orders);
virtual ~ButtonScheduler() = default;
virtual void Execute() = 0;
void Start();
protected:
bool m_pressedLast;
Trigger* m_button;
Command* m_command;
};
} // namespace frc

View File

@@ -0,0 +1,27 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include "Buttons/ButtonScheduler.h"
namespace frc {
class Trigger;
class Command;
class CancelButtonScheduler : public ButtonScheduler {
public:
CancelButtonScheduler(bool last, Trigger* button, Command* orders);
virtual ~CancelButtonScheduler() = default;
virtual void Execute();
private:
bool pressedLast;
};
} // namespace frc

View File

@@ -0,0 +1,24 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include "Buttons/ButtonScheduler.h"
namespace frc {
class Trigger;
class Command;
class HeldButtonScheduler : public ButtonScheduler {
public:
HeldButtonScheduler(bool last, Trigger* button, Command* orders);
virtual ~HeldButtonScheduler() = default;
virtual void Execute();
};
} // namespace frc

View File

@@ -0,0 +1,30 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include "Buttons/Button.h"
namespace frc {
class InternalButton : public Button {
public:
InternalButton() = default;
explicit InternalButton(bool inverted);
virtual ~InternalButton() = default;
void SetInverted(bool inverted);
void SetPressed(bool pressed);
virtual bool Get();
private:
bool m_pressed = false;
bool m_inverted = false;
};
} // namespace frc

View File

@@ -0,0 +1,27 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include "Buttons/Button.h"
#include "GenericHID.h"
namespace frc {
class JoystickButton : public Button {
public:
JoystickButton(GenericHID* joystick, int buttonNumber);
virtual ~JoystickButton() = default;
virtual bool Get();
private:
GenericHID* m_joystick;
int m_buttonNumber;
};
} // namespace frc

View File

@@ -0,0 +1,30 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <memory>
#include <string>
#include "Buttons/Button.h"
namespace frc {
class NetworkButton : public Button {
public:
NetworkButton(const std::string& tableName, const std::string& field);
NetworkButton(std::shared_ptr<ITable> table, const std::string& field);
virtual ~NetworkButton() = default;
virtual bool Get();
private:
std::shared_ptr<ITable> m_netTable;
std::string m_field;
};
} // namespace frc

View File

@@ -0,0 +1,24 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include "Buttons/ButtonScheduler.h"
namespace frc {
class Trigger;
class Command;
class PressedButtonScheduler : public ButtonScheduler {
public:
PressedButtonScheduler(bool last, Trigger* button, Command* orders);
virtual ~PressedButtonScheduler() = default;
virtual void Execute();
};
} // namespace frc

View File

@@ -0,0 +1,24 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include "Buttons/ButtonScheduler.h"
namespace frc {
class Trigger;
class Command;
class ReleasedButtonScheduler : public ButtonScheduler {
public:
ReleasedButtonScheduler(bool last, Trigger* button, Command* orders);
virtual ~ReleasedButtonScheduler() = default;
virtual void Execute();
};
} // namespace frc

View File

@@ -0,0 +1,27 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include "Buttons/ButtonScheduler.h"
namespace frc {
class Trigger;
class Command;
class ToggleButtonScheduler : public ButtonScheduler {
public:
ToggleButtonScheduler(bool last, Trigger* button, Command* orders);
virtual ~ToggleButtonScheduler() = default;
virtual void Execute();
private:
bool pressedLast;
};
} // namespace frc

View File

@@ -0,0 +1,54 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <memory>
#include <string>
#include "SmartDashboard/Sendable.h"
namespace frc {
class Command;
/**
* This class provides an easy way to link commands to inputs.
*
* It is very easy to link a polled input to a command. For instance, you could
* link the trigger button of a joystick to a "score" command or an encoder
* reaching
* a particular value.
*
* It is encouraged that teams write a subclass of Trigger if they want to have
* something unusual (for instance, if they want to react to the user holding
* a button while the robot is reading a certain sensor input). For this, they
* only have to write the {@link Trigger#Get()} method to get the full
* functionality
* of the Trigger class.
*/
class Trigger : public Sendable {
public:
Trigger() = default;
virtual ~Trigger() = default;
bool Grab();
virtual bool Get() = 0;
void WhenActive(Command* command);
void WhileActive(Command* command);
void WhenInactive(Command* command);
void CancelWhenActive(Command* command);
void ToggleWhenActive(Command* command);
void InitTable(std::shared_ptr<ITable> subtable) override;
std::shared_ptr<ITable> GetTable() const override;
std::string GetSmartDashboardType() const override;
protected:
std::shared_ptr<ITable> m_table;
};
} // namespace frc

View File

@@ -0,0 +1,106 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2014-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <stdint.h>
#include "SpeedController.h"
namespace frc {
/**
* Interface for "smart" CAN-based speed controllers.
*/
class CANSpeedController : public SpeedController {
public:
enum ControlMode {
kPercentVbus = 0,
kCurrent = 1,
kSpeed = 2,
kPosition = 3,
kVoltage = 4,
kFollower = 5,
kMotionProfile = 6,
};
// Helper function for the ControlMode enum
virtual bool IsModePID(ControlMode mode) const = 0;
enum Faults {
kCurrentFault = 1,
kTemperatureFault = 2,
kBusVoltageFault = 4,
kGateDriverFault = 8,
/* SRX extensions */
kFwdLimitSwitch = 0x10,
kRevLimitSwitch = 0x20,
kFwdSoftLimit = 0x40,
kRevSoftLimit = 0x80,
};
enum Limits { kForwardLimit = 1, kReverseLimit = 2 };
enum NeutralMode {
/** Use the NeutralMode that is set by the jumper wire on the CAN device */
kNeutralMode_Jumper = 0,
/** Stop the motor's rotation by applying a force. */
kNeutralMode_Brake = 1,
/** Do not attempt to stop the motor. Instead allow it to coast to a stop
without applying resistance. */
kNeutralMode_Coast = 2
};
enum LimitMode {
/** Only use switches for limits */
kLimitMode_SwitchInputsOnly = 0,
/** Use both switches and soft limits */
kLimitMode_SoftPositionLimits = 1,
/* SRX extensions */
/** Disable switches and disable soft limits */
kLimitMode_SrxDisableSwitchInputs = 2,
};
virtual double Get() const = 0;
virtual void Set(double value) = 0;
virtual void StopMotor() = 0;
virtual void Disable() = 0;
virtual void SetP(double p) = 0;
virtual void SetI(double i) = 0;
virtual void SetD(double d) = 0;
virtual void SetPID(double p, double i, double d) = 0;
virtual double GetP() const = 0;
virtual double GetI() const = 0;
virtual double GetD() const = 0;
virtual double GetBusVoltage() const = 0;
virtual double GetOutputVoltage() const = 0;
virtual double GetOutputCurrent() const = 0;
virtual double GetTemperature() const = 0;
virtual double GetPosition() const = 0;
virtual double GetSpeed() const = 0;
virtual bool GetForwardLimitOK() const = 0;
virtual bool GetReverseLimitOK() const = 0;
virtual uint16_t GetFaults() const = 0;
virtual void SetVoltageRampRate(double rampRate) = 0;
virtual int GetFirmwareVersion() const = 0;
virtual void ConfigNeutralMode(NeutralMode mode) = 0;
virtual void ConfigEncoderCodesPerRev(uint16_t codesPerRev) = 0;
virtual void ConfigPotentiometerTurns(uint16_t turns) = 0;
virtual void ConfigSoftPositionLimits(double forwardLimitPosition,
double reverseLimitPosition) = 0;
virtual void DisableSoftPositionLimits() = 0;
virtual void ConfigLimitMode(LimitMode mode) = 0;
virtual void ConfigForwardLimit(double forwardLimitPosition) = 0;
virtual void ConfigReverseLimit(double reverseLimitPosition) = 0;
virtual void ConfigMaxOutputVoltage(double voltage) = 0;
virtual void ConfigFaultTime(double faultTime) = 0;
// Hold off on interface until we figure out ControlMode enums.
// virtual void SetControlMode(ControlMode mode) = 0;
// virtual ControlMode GetControlMode() const = 0;
};
} // namespace frc

View File

@@ -0,0 +1,317 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2014-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <stdint.h>
#include <atomic>
#include <memory>
#include <mutex>
#include <string>
#include <vector>
#include "ErrorBase.h"
#include "cscore.h"
#include "llvm/DenseMap.h"
#include "llvm/StringMap.h"
#include "llvm/StringRef.h"
#include "networktables/NetworkTable.h"
namespace frc {
/**
* Singleton class for creating and keeping camera servers.
* Also publishes camera information to NetworkTables.
*/
class CameraServer : public ErrorBase {
public:
static constexpr uint16_t kBasePort = 1181;
static constexpr int kSize640x480 = 0;
static constexpr int kSize320x240 = 1;
static constexpr int kSize160x120 = 2;
/**
* Get the CameraServer instance.
*/
static CameraServer* GetInstance();
#ifdef __linux__
// USBCamera does not work on anything except linux
/**
* 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.
*
* 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).
*/
cs::UsbCamera StartAutomaticCapture();
/**
* 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
*/
cs::UsbCamera StartAutomaticCapture(int dev);
/**
* 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
*/
cs::UsbCamera StartAutomaticCapture(llvm::StringRef name, int dev);
/**
* 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
*/
cs::UsbCamera StartAutomaticCapture(llvm::StringRef name,
llvm::StringRef path);
#endif
/**
* Start automatically capturing images to send to the dashboard from
* an existing camera.
*
* @param camera Camera
*/
void StartAutomaticCapture(const cs::VideoSource& 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")
*/
cs::AxisCamera AddAxisCamera(llvm::StringRef host);
/**
* 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")
*/
cs::AxisCamera AddAxisCamera(const char* host);
/**
* 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")
*/
cs::AxisCamera AddAxisCamera(const std::string& 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
*/
cs::AxisCamera AddAxisCamera(llvm::ArrayRef<std::string> hosts);
/**
* 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
*/
template <typename T>
cs::AxisCamera AddAxisCamera(std::initializer_list<T> 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")
*/
cs::AxisCamera AddAxisCamera(llvm::StringRef name, llvm::StringRef host);
/**
* 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")
*/
cs::AxisCamera AddAxisCamera(llvm::StringRef name, const char* host);
/**
* 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")
*/
cs::AxisCamera AddAxisCamera(llvm::StringRef name, const std::string& host);
/**
* Adds an Axis IP camera.
*
* @param name The name to give the camera
* @param hosts Array of Camera host IPs/DNS names
*/
cs::AxisCamera AddAxisCamera(llvm::StringRef name,
llvm::ArrayRef<std::string> hosts);
/**
* Adds an Axis IP camera.
*
* @param name The name to give the camera
* @param hosts Array of Camera host IPs/DNS names
*/
template <typename T>
cs::AxisCamera AddAxisCamera(llvm::StringRef name,
std::initializer_list<T> hosts);
/**
* 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().
*/
cs::CvSink GetVideo();
/**
* 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).
*/
cs::CvSink GetVideo(const cs::VideoSource& camera);
/**
* 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
*/
cs::CvSink GetVideo(llvm::StringRef name);
/**
* 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
*/
cs::CvSource PutVideo(llvm::StringRef name, int width, int height);
/**
* Adds a MJPEG server at the next available port.
*
* @param name Server name
*/
cs::MjpegServer AddServer(llvm::StringRef name);
/**
* Adds a MJPEG server.
*
* @param name Server name
*/
cs::MjpegServer AddServer(llvm::StringRef name, int port);
/**
* Adds an already created server.
*
* @param server Server
*/
void AddServer(const cs::VideoSink& server);
/**
* Removes a server by name.
*
* @param name Server name
*/
void RemoveServer(llvm::StringRef 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().
*/
cs::VideoSink GetServer();
/**
* Gets a server by name.
*
* @param name Server name
*/
cs::VideoSink GetServer(llvm::StringRef name);
/**
* Adds an already created camera.
*
* @param camera Camera
*/
void AddCamera(const cs::VideoSource& camera);
/**
* Removes a camera by name.
*
* @param name Camera name
*/
void RemoveCamera(llvm::StringRef name);
/**
* Sets the size of the image to use. Use the public kSize constants to set
* the correct mode, or set it directly on a camera and call the appropriate
* StartAutomaticCapture method.
*
* @deprecated Use SetResolution on the UsbCamera returned by
* StartAutomaticCapture() instead.
* @param size The size to use
*/
void SetSize(int size);
private:
CameraServer();
std::shared_ptr<ITable> GetSourceTable(CS_Source source);
std::vector<std::string> GetSinkStreamValues(CS_Sink sink);
std::vector<std::string> GetSourceStreamValues(CS_Source source);
void UpdateStreamValues();
static constexpr char const* kPublishName = "/CameraPublisher";
std::mutex m_mutex;
std::atomic<int> m_defaultUsbDevice;
std::string m_primarySourceName;
llvm::StringMap<cs::VideoSource> m_sources;
llvm::StringMap<cs::VideoSink> m_sinks;
llvm::DenseMap<CS_Source, std::shared_ptr<ITable>> m_tables;
std::shared_ptr<NetworkTable> m_publishTable;
cs::VideoListener m_videoListener;
int m_tableListener;
int m_nextPort;
std::vector<std::string> m_addresses;
};
} // namespace frc
#include "CameraServer.inc"

View File

@@ -0,0 +1,30 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <string>
#include <vector>
namespace frc {
template <typename T>
inline cs::AxisCamera CameraServer::AddAxisCamera(
std::initializer_list<T> hosts) {
return AddAxisCamera("Axis Camera", hosts);
}
template <typename T>
inline cs::AxisCamera CameraServer::AddAxisCamera(
llvm::StringRef name, std::initializer_list<T> hosts) {
std::vector<std::string> vec;
vec.reserve(hosts.size());
for (const auto& host : hosts) vec.emplace_back(host);
return AddAxisCamera(name, vec);
}
} // namespace frc

View File

@@ -0,0 +1,49 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2015-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <cstddef>
#include <vector>
namespace frc {
/**
* This is a simple circular buffer so we don't need to "bucket brigade" copy
* old values.
*/
template <class T>
class CircularBuffer {
public:
explicit CircularBuffer(size_t size);
void PushFront(T value);
void PushBack(T value);
T PopFront();
T PopBack();
void Resize(size_t size);
void Reset();
T& operator[](size_t index);
const T& operator[](size_t index) const;
private:
std::vector<T> m_data;
// Index of element at front of buffer
size_t m_front = 0;
// Number of elements used in buffer
size_t m_length = 0;
size_t ModuloInc(size_t index);
size_t ModuloDec(size_t index);
};
} // namespace frc
#include "CircularBuffer.inc"

View File

@@ -0,0 +1,189 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2015-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <algorithm>
namespace frc {
template <class T>
CircularBuffer<T>::CircularBuffer(size_t size) : m_data(size, 0) {}
/**
* Push new value onto front of the buffer. The value at the back is overwritten
* if the buffer is full.
*/
template <class T>
void CircularBuffer<T>::PushFront(T value) {
if (m_data.size() == 0) {
return;
}
m_front = ModuloDec(m_front);
m_data[m_front] = value;
if (m_length < m_data.size()) {
m_length++;
}
}
/**
* Push new value onto back of the buffer. The value at the front is overwritten
* if the buffer is full.
*/
template <class T>
void CircularBuffer<T>::PushBack(T value) {
if (m_data.size() == 0) {
return;
}
m_data[(m_front + m_length) % m_data.size()] = value;
if (m_length < m_data.size()) {
m_length++;
} else {
// Increment front if buffer is full to maintain size
m_front = ModuloInc(m_front);
}
}
/**
* Pop value at front of buffer.
*/
template <class T>
T CircularBuffer<T>::PopFront() {
// If there are no elements in the buffer, do nothing
if (m_length == 0) {
return 0;
}
T& temp = m_data[m_front];
m_front = ModuloInc(m_front);
m_length--;
return temp;
}
/**
* Pop value at back of buffer.
*/
template <class T>
T CircularBuffer<T>::PopBack() {
// If there are no elements in the buffer, do nothing
if (m_length == 0) {
return 0;
}
m_length--;
return m_data[(m_front + m_length) % m_data.size()];
}
/**
* Resizes internal buffer to given size.
*/
template <class T>
void CircularBuffer<T>::Resize(size_t size) {
if (size > m_data.size()) {
// Find end of buffer
size_t insertLocation = (m_front + m_length) % m_data.size();
// If insertion location precedes front of buffer, push front index back
if (insertLocation <= m_front) {
m_front += size - m_data.size();
}
// Add elements to end of buffer
m_data.insert(m_data.begin() + insertLocation, size - m_data.size(), 0);
} else if (size < m_data.size()) {
/* 1) Shift element block start at "front" left as many blocks as were
* removed up to but not exceeding buffer[0]
* 2) Shrink buffer, which will remove even more elements automatically if
* necessary
*/
size_t elemsToRemove = m_data.size() - size;
auto frontIter = m_data.begin() + m_front;
if (m_front < elemsToRemove) {
/* Remove elements from end of buffer before shifting start of element
* block. Doing so saves a few copies.
*/
m_data.erase(frontIter + size, m_data.end());
// Shift start of element block to left
m_data.erase(m_data.begin(), frontIter);
// Update metadata
m_front = 0;
} else {
// Shift start of element block to left
m_data.erase(frontIter - elemsToRemove, frontIter);
// Update metadata
m_front -= elemsToRemove;
}
/* Length only changes during a shrink if all unused spaces have been
* removed. Length decreases as used spaces are removed to meet the
* required size.
*/
if (m_length > size) {
m_length = size;
}
}
}
/**
* Sets internal buffer contents to zero.
*/
template <class T>
void CircularBuffer<T>::Reset() {
std::fill(m_data.begin(), m_data.end(), 0);
m_front = 0;
m_length = 0;
}
/**
* @return Element at index starting from front of buffer.
*/
template <class T>
T& CircularBuffer<T>::operator[](size_t index) {
return m_data[(m_front + index) % m_data.size()];
}
/**
* @return Element at index starting from front of buffer.
*/
template <class T>
const T& CircularBuffer<T>::operator[](size_t index) const {
return m_data[(m_front + index) % m_data.size()];
}
/**
* Increment an index modulo the length of the buffer.
*
* @return The result of the modulo operation.
*/
template <class T>
size_t CircularBuffer<T>::ModuloInc(size_t index) {
return (index + 1) % m_data.size();
}
/**
* Decrement an index modulo the length of the buffer.
*
* @return The result of the modulo operation.
*/
template <class T>
size_t CircularBuffer<T>::ModuloDec(size_t index) {
if (index == 0) {
return m_data.size() - 1;
} else {
return index - 1;
}
}
} // namespace frc

View File

@@ -0,0 +1,173 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <memory>
#include <set>
#include <string>
#include "ErrorBase.h"
#include "SmartDashboard/NamedSendable.h"
#include "tables/ITableListener.h"
namespace frc {
class CommandGroup;
class Subsystem;
/**
* The Command class is at the very core of the entire command framework.
* Every command can be started with a call to {@link Command#Start() Start()}.
* Once a command is started it will call {@link Command#Initialize()
* Initialize()}, and then will repeatedly call
* {@link Command#Execute() Execute()} until the
* {@link Command#IsFinished() IsFinished()} returns true. Once it does,
* {@link Command#End() End()} will be called.
*
* <p>However, if at any point while it is running {@link Command#Cancel()
* Cancel()} is called, then the command will be stopped and
* {@link Command#Interrupted() Interrupted()} will be called.</p>
*
* <p>If a command uses a {@link Subsystem}, then it should specify that it does
* so by calling the {@link Command#Requires(Subsystem) Requires(...)} method
* in its constructor. Note that a Command may have multiple requirements, and
* {@link Command#Requires(Subsystem) Requires(...)} should be called for each
* one.</p>
*
* <p>If a command is running and a new command with shared requirements is
* started, then one of two things will happen. If the active command is
* interruptible, then {@link Command#Cancel() Cancel()} will be called and the
* command will be removed to make way for the new one. If the active command
* is not interruptible, the other one will not even be started, and the active
* one will continue functioning.</p>
*
* @see CommandGroup
* @see Subsystem
*/
class Command : public ErrorBase, public NamedSendable, public ITableListener {
friend class CommandGroup;
friend class Scheduler;
public:
Command();
explicit Command(const std::string& name);
explicit Command(double timeout);
Command(const std::string& name, double timeout);
virtual ~Command();
double TimeSinceInitialized() const;
void Requires(Subsystem* s);
bool IsCanceled() const;
void Start();
bool Run();
void Cancel();
bool IsRunning() const;
bool IsInterruptible() const;
void SetInterruptible(bool interruptible);
bool DoesRequire(Subsystem* subsystem) const;
typedef std::set<Subsystem*> SubsystemSet;
SubsystemSet GetRequirements() const;
CommandGroup* GetGroup() const;
void SetRunWhenDisabled(bool run);
bool WillRunWhenDisabled() const;
int GetID() const;
protected:
void SetTimeout(double timeout);
bool IsTimedOut() const;
bool AssertUnlocked(const std::string& message);
void SetParent(CommandGroup* parent);
void ClearRequirements();
virtual void Initialize();
virtual void Execute();
/**
* Returns whether this command is finished.
* If it is, then the command will be removed and {@link Command#end() end()}
* will be called.
*
* <p>It may be useful for a team to reference the {@link Command#isTimedOut()
* isTimedOut()} method for time-sensitive commands.</p>
*
* <p>Returning false will result in the command never ending automatically.
* It may still be cancelled manually or interrupted by another command.
* Returning true will result in the command executing once and finishing
* immediately. We recommend using {@link InstantCommand} for this.</p>
*
* @return whether this command is finished.
* @see Command#isTimedOut() isTimedOut()
*/
virtual bool IsFinished() = 0;
virtual void End();
virtual void Interrupted();
virtual void _Initialize();
virtual void _Interrupted();
virtual void _Execute();
virtual void _End();
virtual void _Cancel();
friend class ConditionalCommand;
private:
void LockChanges();
/*synchronized*/ void Removed();
void StartRunning();
void StartTiming();
/** The name of this command */
std::string m_name;
/** The time since this command was initialized */
double m_startTime = -1;
/** The time (in seconds) before this command "times out" (or -1 if no
* timeout) */
double m_timeout;
/** Whether or not this command has been initialized */
bool m_initialized = false;
/** The requirements (or null if no requirements) */
SubsystemSet m_requirements;
/** Whether or not it is running */
bool m_running = false;
/** Whether or not it is interruptible*/
bool m_interruptible = true;
/** Whether or not it has been canceled */
bool m_canceled = false;
/** Whether or not it has been locked */
bool m_locked = false;
/** Whether this command should run when the robot is disabled */
bool m_runWhenDisabled = false;
/** The {@link CommandGroup} this is in */
CommandGroup* m_parent = nullptr;
int m_commandID = m_commandCounter++;
static int m_commandCounter;
public:
std::string GetName() const override;
void InitTable(std::shared_ptr<ITable> subtable) override;
std::shared_ptr<ITable> GetTable() const override;
std::string GetSmartDashboardType() const override;
void ValueChanged(ITable* source, llvm::StringRef key,
std::shared_ptr<nt::Value> value, bool isNew) override;
protected:
std::shared_ptr<ITable> m_table;
};
} // namespace frc

View File

@@ -0,0 +1,76 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <list>
#include <string>
#include <vector>
#include "Commands/Command.h"
#include "Commands/CommandGroupEntry.h"
namespace frc {
/**
* A {@link CommandGroup} is a list of commands which are executed in sequence.
*
* <p>Commands in a {@link CommandGroup} are added using the {@link
* CommandGroup#AddSequential(Command) AddSequential(...)} method and are
* called sequentially. {@link CommandGroup CommandGroups} are themselves
* {@link Command Commands} and can be given to other
* {@link CommandGroup CommandGroups}.</p>
*
* <p>{@link CommandGroup CommandGroups} will carry all of the requirements of
* their {@link Command subcommands}. Additional requirements can be specified
* by calling {@link CommandGroup#Requires(Subsystem) Requires(...)} normally
* in the constructor.</P>
*
* <p>CommandGroups can also execute commands in parallel, simply by adding them
* using {@link CommandGroup#AddParallel(Command) AddParallel(...)}.</p>
*
* @see Command
* @see Subsystem
*/
class CommandGroup : public Command {
public:
CommandGroup() = default;
explicit CommandGroup(const std::string& name);
virtual ~CommandGroup() = default;
void AddSequential(Command* command);
void AddSequential(Command* command, double timeout);
void AddParallel(Command* command);
void AddParallel(Command* command, double timeout);
bool IsInterruptible() const;
int GetSize() const;
protected:
virtual void Initialize();
virtual void Execute();
virtual bool IsFinished();
virtual void End();
virtual void Interrupted();
virtual void _Initialize();
virtual void _Interrupted();
virtual void _Execute();
virtual void _End();
private:
void CancelConflicts(Command* command);
/** The commands in this group (stored in entries) */
std::vector<CommandGroupEntry> m_commands;
/** The active children in this group (stored in entries) */
std::list<CommandGroupEntry> m_children;
/** The current command, -1 signifies that none have been run */
int m_currentCommandIndex = -1;
};
} // namespace frc

View File

@@ -0,0 +1,31 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
namespace frc {
class Command;
class CommandGroupEntry {
public:
typedef enum {
kSequence_InSequence,
kSequence_BranchPeer,
kSequence_BranchChild
} Sequence;
CommandGroupEntry() = default;
CommandGroupEntry(Command* command, Sequence state, double timeout = -1.0);
bool IsTimedOut() const;
double m_timeout = -1.0;
Command* m_command = nullptr;
Sequence m_state = kSequence_InSequence;
};
} // namespace frc

View File

@@ -0,0 +1,80 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <string>
#include "Commands/Command.h"
#include "Commands/InstantCommand.h"
namespace frc {
/**
* A {@link ConditionalCommand} is a {@link Command} that starts one of two
* commands.
*
* <p>
* A {@link ConditionalCommand} uses m_condition to determine whether it should
* run m_onTrue or m_onFalse.
* </p>
*
* <p>
* A {@link ConditionalCommand} adds the proper {@link Command} to the {@link
* Scheduler} during {@link ConditionalCommand#initialize()} and then {@link
* ConditionalCommand#isFinished()} will return true once that {@link Command}
* has finished executing.
* </p>
*
* <p>
* If no {@link Command} is specified for m_onFalse, the occurrence of that
* condition will be a no-op.
* </p>
*
* @see Command
* @see Scheduler
*/
class ConditionalCommand : public Command {
public:
explicit ConditionalCommand(Command* onTrue, Command* onFalse = nullptr);
ConditionalCommand(const std::string& name, Command* onTrue,
Command* onFalse = nullptr);
virtual ~ConditionalCommand() = default;
protected:
/**
* The Condition to test to determine which Command to run.
*
* @return true if m_onTrue should be run or false if m_onFalse should be run.
*/
virtual bool Condition() = 0;
void _Initialize() override;
void _Cancel() override;
bool IsFinished() override;
void Interrupted() override;
private:
/**
* The Command to execute if {@link ConditionalCommand#Condition()} returns
* true
*/
Command* m_onTrue;
/**
* The Command to execute if {@link ConditionalCommand#Condition()} returns
* false
*/
Command* m_onFalse;
/**
* Stores command chosen by condition
*/
Command* m_chosenCommand = nullptr;
};
} // namespace frc

View File

@@ -0,0 +1,32 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <string>
#include "Commands/Command.h"
namespace frc {
/**
* This command will execute once, then finish immediately afterward.
*
* <p>Subclassing {@link InstantCommand} is shorthand for returning true from
* {@link Command isFinished}.
*/
class InstantCommand : public Command {
public:
explicit InstantCommand(const std::string& name);
InstantCommand() = default;
virtual ~InstantCommand() = default;
protected:
bool IsFinished() override;
};
} // namespace frc

View File

@@ -0,0 +1,61 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <memory>
#include <string>
#include "Commands/Command.h"
#include "PIDController.h"
#include "PIDOutput.h"
#include "PIDSource.h"
namespace frc {
class PIDCommand : public Command, public PIDOutput, public PIDSource {
public:
PIDCommand(const std::string& name, double p, double i, double d);
PIDCommand(const std::string& name, double p, double i, double d,
double period);
PIDCommand(const std::string& name, double p, double i, double d, double f,
double period);
PIDCommand(double p, double i, double d);
PIDCommand(double p, double i, double d, double period);
PIDCommand(double p, double i, double d, double f, double period);
virtual ~PIDCommand() = default;
void SetSetpointRelative(double deltaSetpoint);
// PIDOutput interface
virtual void PIDWrite(double output);
// PIDSource interface
virtual double PIDGet();
protected:
std::shared_ptr<PIDController> GetPIDController() const;
virtual void _Initialize();
virtual void _Interrupted();
virtual void _End();
void SetSetpoint(double setpoint);
double GetSetpoint() const;
double GetPosition();
virtual double ReturnPIDInput() = 0;
virtual void UsePIDOutput(double output) = 0;
private:
/** The internal {@link PIDController} */
std::shared_ptr<PIDController> m_controller;
public:
void InitTable(std::shared_ptr<ITable> subtable) override;
std::string GetSmartDashboardType() const override;
};
} // namespace frc

View File

@@ -0,0 +1,76 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <memory>
#include <string>
#include "Commands/Subsystem.h"
#include "PIDController.h"
#include "PIDOutput.h"
#include "PIDSource.h"
namespace frc {
/**
* This class is designed to handle the case where there is a {@link Subsystem}
* which uses a single {@link PIDController} almost constantly (for instance,
* an elevator which attempts to stay at a constant height).
*
* <p>It provides some convenience methods to run an internal {@link
* PIDController}. It also allows access to the internal {@link PIDController}
* in order to give total control to the programmer.</p>
*
*/
class PIDSubsystem : public Subsystem, public PIDOutput, public PIDSource {
public:
PIDSubsystem(const std::string& name, double p, double i, double d);
PIDSubsystem(const std::string& name, double p, double i, double d, double f);
PIDSubsystem(const std::string& name, double p, double i, double d, double f,
double period);
PIDSubsystem(double p, double i, double d);
PIDSubsystem(double p, double i, double d, double f);
PIDSubsystem(double p, double i, double d, double f, double period);
virtual ~PIDSubsystem() = default;
void Enable();
void Disable();
// PIDOutput interface
virtual void PIDWrite(double output);
// PIDSource interface
virtual double PIDGet();
void SetSetpoint(double setpoint);
void SetSetpointRelative(double deltaSetpoint);
void SetInputRange(double minimumInput, double maximumInput);
void SetOutputRange(double minimumOutput, double maximumOutput);
double GetSetpoint();
double GetPosition();
double GetRate();
virtual void SetAbsoluteTolerance(double absValue);
virtual void SetPercentTolerance(double percent);
virtual bool OnTarget() const;
protected:
std::shared_ptr<PIDController> GetPIDController();
virtual double ReturnPIDInput() = 0;
virtual void UsePIDOutput(double output) = 0;
private:
/** The internal {@link PIDController} */
std::shared_ptr<PIDController> m_controller;
public:
void InitTable(std::shared_ptr<ITable> subtable) override;
std::string GetSmartDashboardType() const override;
};
} // namespace frc

View File

@@ -0,0 +1,28 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <string>
#include "Commands/InstantCommand.h"
namespace frc {
class PrintCommand : public InstantCommand {
public:
explicit PrintCommand(const std::string& message);
virtual ~PrintCommand() = default;
protected:
virtual void Initialize();
private:
std::string m_message;
};
} // namespace frc

View File

@@ -0,0 +1,73 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <list>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <vector>
#include "Commands/Command.h"
#include "ErrorBase.h"
#include "HAL/cpp/priority_mutex.h"
#include "SmartDashboard/NamedSendable.h"
#include "SmartDashboard/SmartDashboard.h"
#include "networktables/NetworkTable.h"
namespace frc {
class ButtonScheduler;
class Subsystem;
class Scheduler : public ErrorBase, public NamedSendable {
public:
static Scheduler* GetInstance();
void AddCommand(Command* command);
void AddButton(ButtonScheduler* button);
void RegisterSubsystem(Subsystem* subsystem);
void Run();
void Remove(Command* command);
void RemoveAll();
void ResetAll();
void SetEnabled(bool enabled);
void UpdateTable();
std::string GetSmartDashboardType() const;
void InitTable(std::shared_ptr<ITable> subTable);
std::shared_ptr<ITable> GetTable() const;
std::string GetName() const;
std::string GetType() const;
private:
Scheduler();
virtual ~Scheduler() = default;
void ProcessCommandAddition(Command* command);
Command::SubsystemSet m_subsystems;
hal::priority_mutex m_buttonsLock;
typedef std::vector<ButtonScheduler*> ButtonVector;
ButtonVector m_buttons;
typedef std::vector<Command*> CommandVector;
hal::priority_mutex m_additionsLock;
CommandVector m_additions;
typedef std::set<Command*> CommandSet;
CommandSet m_commands;
bool m_adding = false;
bool m_enabled = true;
std::vector<std::string> commands;
std::vector<double> ids;
std::vector<double> toCancel;
std::shared_ptr<ITable> m_table;
bool m_runningCommandsChanged = false;
};
} // namespace frc

View File

@@ -0,0 +1,26 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include "Commands/InstantCommand.h"
namespace frc {
class StartCommand : public InstantCommand {
public:
explicit StartCommand(Command* commandToStart);
virtual ~StartCommand() = default;
protected:
virtual void Initialize();
private:
Command* m_commandToFork;
};
} // namespace frc

View File

@@ -0,0 +1,53 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <memory>
#include <string>
#include "ErrorBase.h"
#include "SmartDashboard/NamedSendable.h"
namespace frc {
class Command;
class Subsystem : public ErrorBase, public NamedSendable {
friend class Scheduler;
public:
explicit Subsystem(const std::string& name);
virtual ~Subsystem() = default;
void SetDefaultCommand(Command* command);
Command* GetDefaultCommand();
void SetCurrentCommand(Command* command);
Command* GetCurrentCommand() const;
virtual void Periodic();
virtual void InitDefaultCommand();
private:
void ConfirmCommand();
Command* m_currentCommand = nullptr;
bool m_currentCommandChanged = true;
Command* m_defaultCommand = nullptr;
std::string m_name;
bool m_initializedDefaultCommand = false;
public:
std::string GetName() const override;
void InitTable(std::shared_ptr<ITable> subtable) override;
std::shared_ptr<ITable> GetTable() const override;
std::string GetSmartDashboardType() const override;
protected:
std::shared_ptr<ITable> m_table;
};
} // namespace frc

View File

@@ -0,0 +1,30 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <string>
#include "Commands/Command.h"
namespace frc {
/**
* A {@link TimedCommand} will wait for a timeout before finishing.
* {@link TimedCommand} is used to execute a command for a given amount of time.
*/
class TimedCommand : public Command {
public:
TimedCommand(const std::string& name, double timeout);
explicit TimedCommand(double timeout);
virtual ~TimedCommand() = default;
protected:
bool IsFinished() override;
};
} // namespace frc

View File

@@ -0,0 +1,23 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <string>
#include "Commands/TimedCommand.h"
namespace frc {
class WaitCommand : public TimedCommand {
public:
explicit WaitCommand(double timeout);
WaitCommand(const std::string& name, double timeout);
virtual ~WaitCommand() = default;
};
} // namespace frc

View File

@@ -0,0 +1,26 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <string>
#include "Commands/Command.h"
namespace frc {
class WaitForChildren : public Command {
public:
explicit WaitForChildren(double timeout);
WaitForChildren(const std::string& name, double timeout);
virtual ~WaitForChildren() = default;
protected:
virtual bool IsFinished();
};
} // namespace frc

View File

@@ -0,0 +1,29 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <string>
#include "Commands/Command.h"
namespace frc {
class WaitUntilCommand : public Command {
public:
explicit WaitUntilCommand(double time);
WaitUntilCommand(const std::string& name, double time);
virtual ~WaitUntilCommand() = default;
protected:
virtual bool IsFinished();
private:
double m_time;
};
} // namespace frc

View File

@@ -0,0 +1,69 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2014-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <memory>
#include <string>
#include "HAL/Types.h"
#include "LiveWindow/LiveWindowSendable.h"
#include "SensorBase.h"
#include "tables/ITableListener.h"
namespace frc {
/**
* PCM compressor
*/
class Compressor : public SensorBase,
public LiveWindowSendable,
public ITableListener {
public:
// Default PCM ID is 0
explicit Compressor(int pcmID = GetDefaultSolenoidModule());
virtual ~Compressor() = default;
void Start();
void Stop();
bool Enabled() const;
bool GetPressureSwitchValue() const;
double GetCompressorCurrent() const;
void SetClosedLoopControl(bool on);
bool GetClosedLoopControl() const;
bool GetCompressorCurrentTooHighFault() const;
bool GetCompressorCurrentTooHighStickyFault() const;
bool GetCompressorShortedStickyFault() const;
bool GetCompressorShortedFault() const;
bool GetCompressorNotConnectedStickyFault() const;
bool GetCompressorNotConnectedFault() const;
void ClearAllPCMStickyFaults();
void UpdateTable() override;
void StartLiveWindowMode() override;
void StopLiveWindowMode() override;
std::string GetSmartDashboardType() const override;
void InitTable(std::shared_ptr<ITable> subTable) override;
std::shared_ptr<ITable> GetTable() const override;
void ValueChanged(ITable* source, llvm::StringRef key,
std::shared_ptr<nt::Value> value, bool isNew) override;
protected:
HAL_CompressorHandle m_compressorHandle;
private:
void SetCompressor(bool on);
int m_module;
std::shared_ptr<ITable> m_table;
};
} // namespace frc

View File

@@ -0,0 +1,34 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
namespace frc {
/**
* Interface for Controllers.
* Common interface for controllers. Controllers run control loops, the most
* common are PID controllers and their variants, but this includes anything
* that is controlling an actuator in a separate thread.
*/
class Controller {
public:
virtual ~Controller() = default;
/**
* Allows the control loop to run
*/
virtual void Enable() = 0;
/**
* Stops the control loop from running until explicitly re-enabled by calling
* enable()
*/
virtual void Disable() = 0;
};
} // namespace frc

View File

@@ -0,0 +1,30 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
namespace frc {
class ControllerPower {
public:
static double GetInputVoltage();
static double GetInputCurrent();
static double GetVoltage3V3();
static double GetCurrent3V3();
static bool GetEnabled3V3();
static int GetFaultCount3V3();
static double GetVoltage5V();
static double GetCurrent5V();
static bool GetEnabled5V();
static int GetFaultCount5V();
static double GetVoltage6V();
static double GetCurrent6V();
static bool GetEnabled6V();
static int GetFaultCount6V();
};
} // namespace frc

View File

@@ -0,0 +1,118 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <memory>
#include <string>
#include "AnalogTrigger.h"
#include "CounterBase.h"
#include "HAL/Counter.h"
#include "HAL/Types.h"
#include "LiveWindow/LiveWindowSendable.h"
#include "SensorBase.h"
namespace frc {
class DigitalGlitchFilter;
/**
* Class for counting the number of ticks on a digital input channel.
*
* This is a general purpose class for counting repetitive events. It can return
* the number of counts, the period of the most recent cycle, and detect when
* the signal being counted has stopped by supplying a maximum cycle time.
*
* All counters will immediately start counting - Reset() them if you need them
* to be zeroed before use.
*/
class Counter : public SensorBase,
public CounterBase,
public LiveWindowSendable {
public:
enum Mode {
kTwoPulse = 0,
kSemiperiod = 1,
kPulseLength = 2,
kExternalDirection = 3
};
explicit Counter(Mode mode = kTwoPulse);
explicit Counter(int channel);
explicit Counter(DigitalSource* source);
explicit Counter(std::shared_ptr<DigitalSource> source);
explicit Counter(const AnalogTrigger& trigger);
Counter(EncodingType encodingType, DigitalSource* upSource,
DigitalSource* downSource, bool inverted);
Counter(EncodingType encodingType, std::shared_ptr<DigitalSource> upSource,
std::shared_ptr<DigitalSource> downSource, bool inverted);
virtual ~Counter();
void SetUpSource(int channel);
void SetUpSource(AnalogTrigger* analogTrigger, AnalogTriggerType triggerType);
void SetUpSource(std::shared_ptr<AnalogTrigger> analogTrigger,
AnalogTriggerType triggerType);
void SetUpSource(DigitalSource* source);
void SetUpSource(std::shared_ptr<DigitalSource> source);
void SetUpSource(DigitalSource& source);
void SetUpSourceEdge(bool risingEdge, bool fallingEdge);
void ClearUpSource();
void SetDownSource(int channel);
void SetDownSource(AnalogTrigger* analogTrigger,
AnalogTriggerType triggerType);
void SetDownSource(std::shared_ptr<AnalogTrigger> analogTrigger,
AnalogTriggerType triggerType);
void SetDownSource(DigitalSource* source);
void SetDownSource(std::shared_ptr<DigitalSource> source);
void SetDownSource(DigitalSource& source);
void SetDownSourceEdge(bool risingEdge, bool fallingEdge);
void ClearDownSource();
void SetUpDownCounterMode();
void SetExternalDirectionMode();
void SetSemiPeriodMode(bool highSemiPeriod);
void SetPulseLengthMode(double threshold);
void SetReverseDirection(bool reverseDirection);
// CounterBase interface
int Get() const override;
void Reset() override;
double GetPeriod() const override;
void SetMaxPeriod(double maxPeriod) override;
void SetUpdateWhenEmpty(bool enabled);
bool GetStopped() const override;
bool GetDirection() const override;
void SetSamplesToAverage(int samplesToAverage);
int GetSamplesToAverage() const;
int GetFPGAIndex() const { return m_index; }
void UpdateTable() override;
void StartLiveWindowMode() override;
void StopLiveWindowMode() override;
std::string GetSmartDashboardType() const override;
void InitTable(std::shared_ptr<ITable> subTable) override;
std::shared_ptr<ITable> GetTable() const override;
protected:
// Makes the counter count up.
std::shared_ptr<DigitalSource> m_upSource;
// Makes the counter count down.
std::shared_ptr<DigitalSource> m_downSource;
// The FPGA counter object
HAL_CounterHandle m_counter = HAL_kInvalidHandle;
private:
int m_index = 0; ///< The index of this counter.
std::shared_ptr<ITable> m_table;
friend class DigitalGlitchFilter;
};
} // namespace frc

View File

@@ -0,0 +1,33 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
namespace frc {
/**
* Interface for counting the number of ticks on a digital input channel.
* Encoders, Gear tooth sensors, and counters should all subclass this so it can
* be used to build more advanced classes for control and driving.
*
* All counters will immediately start counting - Reset() them if you need them
* to be zeroed before use.
*/
class CounterBase {
public:
enum EncodingType { k1X, k2X, k4X };
virtual ~CounterBase() = default;
virtual int Get() const = 0;
virtual void Reset() = 0;
virtual double GetPeriod() const = 0;
virtual void SetMaxPeriod(double maxPeriod) = 0;
virtual bool GetStopped() const = 0;
virtual bool GetDirection() const = 0;
};
} // namespace frc

View File

@@ -0,0 +1,58 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2015-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <stdint.h>
#include <array>
#include "DigitalSource.h"
#include "HAL/cpp/priority_mutex.h"
namespace frc {
class Encoder;
class Counter;
/**
* Class to enable glitch filtering on a set of digital inputs.
* This class will manage adding and removing digital inputs from a FPGA glitch
* filter. The filter lets the user configure the time that an input must remain
* high or low before it is classified as high or low.
*/
class DigitalGlitchFilter : public SensorBase {
public:
DigitalGlitchFilter();
~DigitalGlitchFilter();
void Add(DigitalSource* input);
void Add(Encoder* input);
void Add(Counter* input);
void Remove(DigitalSource* input);
void Remove(Encoder* input);
void Remove(Counter* input);
void SetPeriodCycles(int fpga_cycles);
void SetPeriodNanoSeconds(uint64_t nanoseconds);
int GetPeriodCycles();
uint64_t GetPeriodNanoSeconds();
private:
// Sets the filter for the input to be the requested index. A value of 0
// disables the filter, and the filter value must be between 1 and 3,
// inclusive.
void DoAdd(DigitalSource* input, int requested_index);
int m_channelIndex = -1;
static hal::priority_mutex m_mutex;
static std::array<bool, 3> m_filterAllocated;
};
} // namespace frc

View File

@@ -0,0 +1,55 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <memory>
#include <string>
#include "DigitalSource.h"
#include "LiveWindow/LiveWindowSendable.h"
namespace frc {
class DigitalGlitchFilter;
/**
* Class to read a digital input.
* This class will read digital inputs and return the current value on the
* channel. Other devices such as encoders, gear tooth sensors, etc. that are
* implemented elsewhere will automatically allocate digital inputs and outputs
* as required. This class is only for devices like switches etc. that aren't
* implemented anywhere else.
*/
class DigitalInput : public DigitalSource, public LiveWindowSendable {
public:
explicit DigitalInput(int channel);
virtual ~DigitalInput();
bool Get() const;
int GetChannel() const override;
// Digital Source Interface
HAL_Handle GetPortHandleForRouting() const override;
AnalogTriggerType GetAnalogTriggerTypeForRouting() const override;
bool IsAnalogTrigger() const override;
void UpdateTable();
void StartLiveWindowMode();
void StopLiveWindowMode();
std::string GetSmartDashboardType() const;
void InitTable(std::shared_ptr<ITable> subTable);
std::shared_ptr<ITable> GetTable() const;
private:
int m_channel;
HAL_DigitalHandle m_handle;
std::shared_ptr<ITable> m_table;
friend class DigitalGlitchFilter;
};
} // namespace frc

View File

@@ -0,0 +1,64 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <memory>
#include <string>
#include "DigitalSource.h"
#include "HAL/Types.h"
#include "LiveWindow/LiveWindowSendable.h"
#include "tables/ITableListener.h"
namespace frc {
/**
* Class to write to digital outputs.
* Write values to the digital output channels. Other devices implemented
* elsewhere will allocate channels automatically so for those devices it
* shouldn't be done here.
*/
class DigitalOutput : public DigitalSource,
public ITableListener,
public LiveWindowSendable {
public:
explicit DigitalOutput(int channel);
virtual ~DigitalOutput();
void Set(bool value);
bool Get() const;
int GetChannel() const override;
void Pulse(double length);
bool IsPulsing() const;
void SetPWMRate(double rate);
void EnablePWM(double initialDutyCycle);
void DisablePWM();
void UpdateDutyCycle(double dutyCycle);
// Digital Source Interface
HAL_Handle GetPortHandleForRouting() const override;
AnalogTriggerType GetAnalogTriggerTypeForRouting() const override;
bool IsAnalogTrigger() const override;
void ValueChanged(ITable* source, llvm::StringRef key,
std::shared_ptr<nt::Value> value, bool isNew) override;
void UpdateTable();
void StartLiveWindowMode();
void StopLiveWindowMode();
std::string GetSmartDashboardType() const;
void InitTable(std::shared_ptr<ITable> subTable);
std::shared_ptr<ITable> GetTable() const;
private:
int m_channel;
HAL_DigitalHandle m_handle;
HAL_DigitalPWMHandle m_pwmGenerator;
std::shared_ptr<ITable> m_table;
};
} // namespace frc

View File

@@ -0,0 +1,34 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include "HAL/Types.h"
#include "InterruptableSensorBase.h"
namespace frc {
/**
* DigitalSource Interface.
* The DigitalSource represents all the possible inputs for a counter or a
* quadrature encoder. The source may be
* either a digital input or an analog input. If the caller just provides a
* channel, then a digital input will be
* constructed and freed when finished for the source. The source can either be
* a digital input or analog trigger
* but not both.
*/
class DigitalSource : public InterruptableSensorBase {
public:
virtual ~DigitalSource() = default;
virtual HAL_Handle GetPortHandleForRouting() const = 0;
virtual AnalogTriggerType GetAnalogTriggerTypeForRouting() const = 0;
virtual bool IsAnalogTrigger() const = 0;
virtual int GetChannel() const = 0;
};
} // namespace frc

View File

@@ -0,0 +1,61 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <memory>
#include <string>
#include "HAL/Types.h"
#include "LiveWindow/LiveWindowSendable.h"
#include "SolenoidBase.h"
#include "tables/ITableListener.h"
namespace frc {
/**
* DoubleSolenoid class for running 2 channels of high voltage Digital Output
* (PCM).
*
* The DoubleSolenoid class is typically used for pneumatics solenoids that
* have two positions controlled by two separate channels.
*/
class DoubleSolenoid : public SolenoidBase,
public LiveWindowSendable,
public ITableListener {
public:
enum Value { kOff, kForward, kReverse };
explicit DoubleSolenoid(int forwardChannel, int reverseChannel);
DoubleSolenoid(int moduleNumber, int forwardChannel, int reverseChannel);
virtual ~DoubleSolenoid();
virtual void Set(Value value);
virtual Value Get() const;
bool IsFwdSolenoidBlackListed() const;
bool IsRevSolenoidBlackListed() const;
void ValueChanged(ITable* source, llvm::StringRef key,
std::shared_ptr<nt::Value> value, bool isNew);
void UpdateTable();
void StartLiveWindowMode();
void StopLiveWindowMode();
std::string GetSmartDashboardType() const;
void InitTable(std::shared_ptr<ITable> subTable);
std::shared_ptr<ITable> GetTable() const;
private:
int m_forwardChannel; ///< The forward channel on the module to control.
int m_reverseChannel; ///< The reverse channel on the module to control.
int m_forwardMask; ///< The mask for the forward channel.
int m_reverseMask; ///< The mask for the reverse channel.
HAL_SolenoidHandle m_forwardHandle = HAL_kInvalidHandle;
HAL_SolenoidHandle m_reverseHandle = HAL_kInvalidHandle;
std::shared_ptr<ITable> m_table;
};
} // namespace frc

View File

@@ -0,0 +1,134 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <atomic>
#include <memory>
#include <string>
#include <thread>
#include "HAL/DriverStation.h"
#include "HAL/cpp/priority_mutex.h"
#include "RobotState.h"
#include "SensorBase.h"
#include "llvm/StringRef.h"
namespace frc {
/**
* Provide access to the network communication data to / from the Driver
* Station.
*/
class DriverStation : public SensorBase, public RobotStateInterface {
public:
enum Alliance { kRed, kBlue, kInvalid };
virtual ~DriverStation();
static DriverStation& GetInstance();
static void ReportError(llvm::StringRef error);
static void ReportWarning(llvm::StringRef error);
static void ReportError(bool is_error, int code, llvm::StringRef error,
llvm::StringRef location, llvm::StringRef stack);
static const int kJoystickPorts = 6;
double GetStickAxis(int stick, int axis);
int GetStickPOV(int stick, int pov);
int GetStickButtons(int stick) const;
bool GetStickButton(int stick, int button);
int GetStickAxisCount(int stick) const;
int GetStickPOVCount(int stick) const;
int GetStickButtonCount(int stick) const;
bool GetJoystickIsXbox(int stick) const;
int GetJoystickType(int stick) const;
std::string GetJoystickName(int stick) const;
int GetJoystickAxisType(int stick, int axis) const;
bool IsEnabled() const override;
bool IsDisabled() const override;
bool IsAutonomous() const override;
bool IsOperatorControl() const override;
bool IsTest() const override;
bool IsDSAttached() const;
bool IsNewControlData() const;
bool IsFMSAttached() const;
bool IsSysActive() const;
bool IsBrownedOut() const;
Alliance GetAlliance() const;
int GetLocation() const;
void WaitForData();
bool WaitForData(double timeout);
double GetMatchTime() const;
double GetBatteryVoltage() const;
/** Only to be used to tell the Driver Station what code you claim to be
* executing for diagnostic purposes only
* @param entering If true, starting disabled code; if false, leaving disabled
* code */
void InDisabled(bool entering) { m_userInDisabled = entering; }
/** Only to be used to tell the Driver Station what code you claim to be
* executing for diagnostic purposes only
* @param entering If true, starting autonomous code; if false, leaving
* autonomous code */
void InAutonomous(bool entering) { m_userInAutonomous = entering; }
/** Only to be used to tell the Driver Station what code you claim to be
* executing for diagnostic purposes only
* @param entering If true, starting teleop code; if false, leaving teleop
* code */
void InOperatorControl(bool entering) { m_userInTeleop = entering; }
/** Only to be used to tell the Driver Station what code you claim to be
* executing for diagnostic purposes only
* @param entering If true, starting test code; if false, leaving test code */
void InTest(bool entering) { m_userInTest = entering; }
protected:
void GetData();
private:
DriverStation();
void ReportJoystickUnpluggedError(llvm::StringRef message);
void ReportJoystickUnpluggedWarning(llvm::StringRef message);
void Run();
void UpdateControlWord(bool force, HAL_ControlWord& controlWord) const;
// Joystick User Data
std::unique_ptr<HAL_JoystickAxes[]> m_joystickAxes;
std::unique_ptr<HAL_JoystickPOVs[]> m_joystickPOVs;
std::unique_ptr<HAL_JoystickButtons[]> m_joystickButtons;
std::unique_ptr<HAL_JoystickDescriptor[]> m_joystickDescriptor;
// Joystick Cached Data
std::unique_ptr<HAL_JoystickAxes[]> m_joystickAxesCache;
std::unique_ptr<HAL_JoystickPOVs[]> m_joystickPOVsCache;
std::unique_ptr<HAL_JoystickButtons[]> m_joystickButtonsCache;
std::unique_ptr<HAL_JoystickDescriptor[]> m_joystickDescriptorCache;
// Internal Driver Station thread
std::thread m_dsThread;
std::atomic<bool> m_isRunning{false};
mutable hal::priority_mutex m_joystickDataMutex;
// Robot state status variables
bool m_userInDisabled = false;
bool m_userInAutonomous = false;
bool m_userInTeleop = false;
bool m_userInTest = false;
// Control word variables
mutable HAL_ControlWord m_controlWordCache;
mutable std::chrono::steady_clock::time_point m_lastControlWordUpdate;
mutable hal::priority_mutex m_controlWordMutex;
double m_nextMessageTime = 0;
};
} // namespace frc

View File

@@ -0,0 +1,109 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <memory>
#include <string>
#include "Counter.h"
#include "CounterBase.h"
#include "HAL/Encoder.h"
#include "LiveWindow/LiveWindowSendable.h"
#include "PIDSource.h"
#include "SensorBase.h"
namespace frc {
class DigitalSource;
class DigitalGlitchFilter;
/**
* Class to read quad encoders.
*
* Quadrature encoders are devices that count shaft rotation and can sense
* direction. The output of the QuadEncoder class is an integer that can count
* either up or down, and can go negative for reverse direction counting. When
* creating QuadEncoders, a direction is supplied that changes the sense of the
* output to make code more readable if the encoder is mounted such that forward
* movement generates negative values. Quadrature encoders have two digital
* outputs, an A Channel and a B Channel that are out of phase with each other
* to allow the FPGA to do direction sensing.
*
* All encoders will immediately start counting - Reset() them if you need them
* to be zeroed before use.
*/
class Encoder : public SensorBase,
public CounterBase,
public PIDSource,
public LiveWindowSendable {
public:
enum IndexingType {
kResetWhileHigh,
kResetWhileLow,
kResetOnFallingEdge,
kResetOnRisingEdge
};
Encoder(int aChannel, int bChannel, bool reverseDirection = false,
EncodingType encodingType = k4X);
Encoder(std::shared_ptr<DigitalSource> aSource,
std::shared_ptr<DigitalSource> bSource, bool reverseDirection = false,
EncodingType encodingType = k4X);
Encoder(DigitalSource* aSource, DigitalSource* bSource,
bool reverseDirection = false, EncodingType encodingType = k4X);
Encoder(DigitalSource& aSource, DigitalSource& bSource,
bool reverseDirection = false, EncodingType encodingType = k4X);
virtual ~Encoder();
// CounterBase interface
int Get() const override;
int GetRaw() const;
int GetEncodingScale() const;
void Reset() override;
double GetPeriod() const override;
void SetMaxPeriod(double maxPeriod) override;
bool GetStopped() const override;
bool GetDirection() const override;
double GetDistance() const;
double GetRate() const;
void SetMinRate(double minRate);
void SetDistancePerPulse(double distancePerPulse);
void SetReverseDirection(bool reverseDirection);
void SetSamplesToAverage(int samplesToAverage);
int GetSamplesToAverage() const;
double PIDGet() override;
void SetIndexSource(int channel, IndexingType type = kResetOnRisingEdge);
void SetIndexSource(const DigitalSource& source,
IndexingType type = kResetOnRisingEdge);
void UpdateTable() override;
void StartLiveWindowMode() override;
void StopLiveWindowMode() override;
std::string GetSmartDashboardType() const override;
void InitTable(std::shared_ptr<ITable> subTable) override;
std::shared_ptr<ITable> GetTable() const override;
int GetFPGAIndex() const;
private:
void InitEncoder(bool reverseDirection, EncodingType encodingType);
double DecodingScaleFactor() const;
std::shared_ptr<DigitalSource> m_aSource; // the A phase of the quad encoder
std::shared_ptr<DigitalSource> m_bSource; // the B phase of the quad encoder
std::unique_ptr<DigitalSource> m_indexSource = nullptr;
HAL_EncoderHandle m_encoder = HAL_kInvalidHandle;
std::shared_ptr<ITable> m_table;
friend class DigitalGlitchFilter;
};
} // namespace frc

View File

@@ -0,0 +1,65 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <stdint.h>
#include <string>
#include "Base.h"
#include "llvm/StringRef.h"
#ifdef _WIN32
#include <Windows.h>
// Windows.h defines #define GetMessage GetMessageW, which we don't want.
#undef GetMessage
#endif
namespace frc {
// Forward declarations
class ErrorBase;
/**
* Error object represents a library error.
*/
class Error {
public:
typedef int Code;
Error() = default;
Error(const Error&) = delete;
Error& operator=(const Error&) = delete;
void Clone(const Error& error);
Code GetCode() const;
std::string GetMessage() const;
std::string GetFilename() const;
std::string GetFunction() const;
int GetLineNumber() const;
const ErrorBase* GetOriginatingObject() const;
double GetTimestamp() const;
void Clear();
void Set(Code code, llvm::StringRef contextMessage, llvm::StringRef filename,
llvm::StringRef function, int lineNumber,
const ErrorBase* originatingObject);
private:
void Report();
Code m_code = 0;
std::string m_message;
std::string m_filename;
std::string m_function;
int m_lineNumber = 0;
const ErrorBase* m_originatingObject = nullptr;
double m_timestamp = 0.0;
};
} // namespace frc

View File

@@ -0,0 +1,120 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include "Base.h"
#include "Error.h"
#include "HAL/cpp/priority_mutex.h"
#include "llvm/StringRef.h"
#define wpi_setErrnoErrorWithContext(context) \
this->SetErrnoError((context), __FILE__, __FUNCTION__, __LINE__)
#define wpi_setErrnoError() wpi_setErrnoErrorWithContext("")
#define wpi_setImaqErrorWithContext(code, context) \
do { \
if ((code) != 0) \
this->SetImaqError((code), (context), __FILE__, __FUNCTION__, __LINE__); \
} while (0)
#define wpi_setErrorWithContext(code, context) \
do { \
if ((code) != 0) \
this->SetError((code), (context), __FILE__, __FUNCTION__, __LINE__); \
} while (0)
#define wpi_setErrorWithContextRange(code, min, max, req, context) \
do { \
if ((code) != 0) \
this->SetErrorRange((code), (min), (max), (req), (context), __FILE__, \
__FUNCTION__, __LINE__); \
} while (0)
#define wpi_setError(code) wpi_setErrorWithContext(code, "")
#define wpi_setStaticErrorWithContext(object, code, context) \
do { \
if ((code) != 0) \
object->SetError((code), (context), __FILE__, __FUNCTION__, __LINE__); \
} while (0)
#define wpi_setStaticError(object, code) \
wpi_setStaticErrorWithContext(object, code, "")
#define wpi_setGlobalErrorWithContext(code, context) \
do { \
if ((code) != 0) \
::frc::ErrorBase::SetGlobalError((code), (context), __FILE__, \
__FUNCTION__, __LINE__); \
} while (0)
#define wpi_setGlobalError(code) wpi_setGlobalErrorWithContext(code, "")
#define wpi_setWPIErrorWithContext(error, context) \
this->SetWPIError((wpi_error_s_##error), (wpi_error_value_##error), \
(context), __FILE__, __FUNCTION__, __LINE__)
#define wpi_setWPIError(error) (wpi_setWPIErrorWithContext(error, ""))
#define wpi_setStaticWPIErrorWithContext(object, error, context) \
object->SetWPIError((wpi_error_s_##error), (context), __FILE__, \
__FUNCTION__, __LINE__)
#define wpi_setStaticWPIError(object, error) \
wpi_setStaticWPIErrorWithContext(object, error, "")
#define wpi_setGlobalWPIErrorWithContext(error, context) \
::frc::ErrorBase::SetGlobalWPIError((wpi_error_s_##error), (context), \
__FILE__, __FUNCTION__, __LINE__)
#define wpi_setGlobalWPIError(error) wpi_setGlobalWPIErrorWithContext(error, "")
namespace frc {
/**
* Base class for most objects.
* ErrorBase is the base class for most objects since it holds the generated
* error
* for that object. In addition, there is a single instance of a global error
* object
*/
class ErrorBase {
// TODO: Consider initializing instance variables and cleanup in destructor
public:
ErrorBase() = default;
virtual ~ErrorBase() = default;
ErrorBase(const ErrorBase&) = delete;
ErrorBase& operator=(const ErrorBase&) = delete;
virtual Error& GetError();
virtual const Error& GetError() const;
virtual void SetErrnoError(llvm::StringRef contextMessage,
llvm::StringRef filename, llvm::StringRef function,
int lineNumber) const;
virtual void SetImaqError(int success, llvm::StringRef contextMessage,
llvm::StringRef filename, llvm::StringRef function,
int lineNumber) const;
virtual void SetError(Error::Code code, llvm::StringRef contextMessage,
llvm::StringRef filename, llvm::StringRef function,
int lineNumber) const;
virtual void SetErrorRange(Error::Code code, int32_t minRange,
int32_t maxRange, int32_t requestedValue,
llvm::StringRef contextMessage,
llvm::StringRef filename, llvm::StringRef function,
int lineNumber) const;
virtual void SetWPIError(llvm::StringRef errorMessage, Error::Code code,
llvm::StringRef contextMessage,
llvm::StringRef filename, llvm::StringRef function,
int lineNumber) const;
virtual void CloneError(const ErrorBase& rhs) const;
virtual void ClearError() const;
virtual bool StatusIsFatal() const;
static void SetGlobalError(Error::Code code, llvm::StringRef contextMessage,
llvm::StringRef filename, llvm::StringRef function,
int lineNumber);
static void SetGlobalWPIError(llvm::StringRef errorMessage,
llvm::StringRef contextMessage,
llvm::StringRef filename,
llvm::StringRef function, int lineNumber);
static Error& GetGlobalError();
protected:
mutable Error m_error;
// TODO: Replace globalError with a global list of all errors.
static hal::priority_mutex _globalErrorMutex;
static Error _globalError;
};
} // namespace frc

View File

@@ -0,0 +1,54 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2015-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <memory>
#include "PIDSource.h"
namespace frc {
/**
* Interface for filters
*/
class Filter : public PIDSource {
public:
explicit Filter(std::shared_ptr<PIDSource> source);
virtual ~Filter() = default;
// PIDSource interface
void SetPIDSourceType(PIDSourceType pidSource) override;
PIDSourceType GetPIDSourceType() const;
double PIDGet() override = 0;
/**
* Returns the current filter estimate without also inserting new data as
* PIDGet() would do.
*
* @return The current filter estimate
*/
virtual double Get() const = 0;
/**
* Reset the filter state
*/
virtual void Reset() = 0;
protected:
/**
* Calls PIDGet() of source
*
* @return Current value of source
*/
double PIDGetSource();
private:
std::shared_ptr<PIDSource> m_source;
};
} // namespace frc

View File

@@ -0,0 +1,106 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2015-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <initializer_list>
#include <memory>
#include <vector>
#include "CircularBuffer.h"
#include "Filter.h"
namespace frc {
/**
* This class implements a linear, digital filter. All types of FIR and IIR
* filters are supported. Static factory methods are provided to create commonly
* used types of filters.
*
* Filters are of the form:<br>
* y[n] = (b0 * x[n] + b1 * x[n-1] + … + bP * x[n-P]) -
* (a0 * y[n-1] + a2 * y[n-2] + … + aQ * y[n-Q])
*
* Where:<br>
* y[n] is the output at time "n"<br>
* x[n] is the input at time "n"<br>
* y[n-1] is the output from the LAST time step ("n-1")<br>
* x[n-1] is the input from the LAST time step ("n-1")<br>
* b0 … bP are the "feedforward" (FIR) gains<br>
* a0 … aQ are the "feedback" (IIR) gains<br>
* IMPORTANT! Note the "-" sign in front of the feedback term! This is a common
* convention in signal processing.
*
* What can linear filters do? Basically, they can filter, or diminish, the
* effects of undesirable input frequencies. High frequencies, or rapid changes,
* can be indicative of sensor noise or be otherwise undesirable. A "low pass"
* filter smooths out the signal, reducing the impact of these high frequency
* components. Likewise, a "high pass" filter gets rid of slow-moving signal
* components, letting you detect large changes more easily.
*
* Example FRC applications of filters:
* - Getting rid of noise from an analog sensor input (note: the roboRIO's FPGA
* can do this faster in hardware)
* - Smoothing out joystick input to prevent the wheels from slipping or the
* robot from tipping
* - Smoothing motor commands so that unnecessary strain isn't put on
* electrical or mechanical components
* - If you use clever gains, you can make a PID controller out of this class!
*
* For more on filters, I highly recommend the following articles:<br>
* http://en.wikipedia.org/wiki/Linear_filter<br>
* http://en.wikipedia.org/wiki/Iir_filter<br>
* http://en.wikipedia.org/wiki/Fir_filter<br>
*
* Note 1: PIDGet() should be called by the user on a known, regular period.
* You can set up a Notifier to do this (look at the WPILib PIDController
* class), or do it "inline" with code in a periodic function.
*
* Note 2: For ALL filters, gains are necessarily a function of frequency. If
* you make a filter that works well for you at, say, 100Hz, you will most
* definitely need to adjust the gains if you then want to run it at 200Hz!
* Combining this with Note 1 - the impetus is on YOU as a developer to make
* sure PIDGet() gets called at the desired, constant frequency!
*/
class LinearDigitalFilter : public Filter {
public:
LinearDigitalFilter(std::shared_ptr<PIDSource> source,
std::initializer_list<double> ffGains,
std::initializer_list<double> fbGains);
LinearDigitalFilter(std::shared_ptr<PIDSource> source,
std::initializer_list<double> ffGains,
const std::vector<double>& fbGains);
LinearDigitalFilter(std::shared_ptr<PIDSource> source,
const std::vector<double>& ffGains,
std::initializer_list<double> fbGains);
LinearDigitalFilter(std::shared_ptr<PIDSource> source,
const std::vector<double>& ffGains,
const std::vector<double>& fbGains);
// Static methods to create commonly used filters
static LinearDigitalFilter SinglePoleIIR(std::shared_ptr<PIDSource> source,
double timeConstant, double period);
static LinearDigitalFilter HighPass(std::shared_ptr<PIDSource> source,
double timeConstant, double period);
static LinearDigitalFilter MovingAverage(std::shared_ptr<PIDSource> source,
int taps);
// Filter interface
double Get() const override;
void Reset() override;
// PIDSource interface
double PIDGet() override;
private:
CircularBuffer<double> m_inputs;
CircularBuffer<double> m_outputs;
std::vector<double> m_inputGains;
std::vector<double> m_outputGains;
};
} // namespace frc

View File

@@ -0,0 +1,26 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include "GenericHID.h"
namespace frc {
/**
* Gamepad Interface.
*/
class GamepadBase : public GenericHID {
public:
explicit GamepadBase(int port);
virtual ~GamepadBase() = default;
virtual bool GetBumper(JoystickHand hand = kRightHand) const = 0;
virtual bool GetStickButton(JoystickHand hand) const = 0;
};
} // namespace frc

View File

@@ -0,0 +1,37 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <memory>
#include <string>
#include "Counter.h"
namespace frc {
/**
* Alias for counter class.
* Implement the gear tooth sensor supplied by FIRST. Currently there is no
* reverse sensing on the gear tooth sensor, but in future versions we might
* implement the necessary timing in the FPGA to sense direction.
*/
class GearTooth : public Counter {
public:
/// 55 uSec for threshold
static constexpr double kGearToothThreshold = 55e-6;
explicit GearTooth(int channel, bool directionSensitive = false);
explicit GearTooth(DigitalSource* source, bool directionSensitive = false);
explicit GearTooth(std::shared_ptr<DigitalSource> source,
bool directionSensitive = false);
virtual ~GearTooth() = default;
void EnableDirectionSensing(bool directionSensitive);
std::string GetSmartDashboardType() const override;
};
} // namespace frc

View File

@@ -0,0 +1,75 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <stdint.h>
#include <string>
namespace frc {
class DriverStation;
/**
* GenericHID Interface.
*/
class GenericHID {
public:
typedef enum { kLeftRumble, kRightRumble } RumbleType;
typedef enum {
kUnknown = -1,
kXInputUnknown = 0,
kXInputGamepad = 1,
kXInputWheel = 2,
kXInputArcadeStick = 3,
kXInputFlightStick = 4,
kXInputDancePad = 5,
kXInputGuitar = 6,
kXInputGuitar2 = 7,
kXInputDrumKit = 8,
kXInputGuitar3 = 11,
kXInputArcadePad = 19,
kHIDJoystick = 20,
kHIDGamepad = 21,
kHIDDriving = 22,
kHIDFlight = 23,
kHID1stPerson = 24
} HIDType;
enum JoystickHand { kLeftHand = 0, kRightHand = 1 };
explicit GenericHID(int port);
virtual ~GenericHID() = default;
virtual double GetX(JoystickHand hand = kRightHand) const = 0;
virtual double GetY(JoystickHand hand = kRightHand) const = 0;
virtual double GetRawAxis(int axis) const;
bool GetRawButton(int button) const;
int GetPOV(int pov = 0) const;
int GetPOVCount() const;
int GetPort() const;
GenericHID::HIDType GetType() const;
std::string GetName() const;
void SetOutput(int outputNumber, bool value);
void SetOutputs(int value);
void SetRumble(RumbleType type, double value);
private:
DriverStation& m_ds;
int m_port;
int m_outputs = 0;
uint16_t m_leftRumble = 0;
uint16_t m_rightRumble = 0;
};
} // namespace frc

View File

@@ -0,0 +1,45 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <memory>
#include <string>
#include "LiveWindow/LiveWindowSendable.h"
#include "PIDSource.h"
#include "SensorBase.h"
#include "interfaces/Gyro.h"
namespace frc {
/**
* GyroBase is the common base class for Gyro implementations such as
* AnalogGyro.
*/
class GyroBase : public Gyro,
public SensorBase,
public PIDSource,
public LiveWindowSendable {
public:
virtual ~GyroBase() = default;
// PIDSource interface
double PIDGet() override;
void UpdateTable() override;
void StartLiveWindowMode() override;
void StopLiveWindowMode() override;
std::string GetSmartDashboardType() const override;
void InitTable(std::shared_ptr<ITable> subTable) override;
std::shared_ptr<ITable> GetTable() const override;
private:
std::shared_ptr<ITable> m_table;
};
} // namespace frc

View File

@@ -0,0 +1,29 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
namespace frc {
class HLUsageReportingInterface {
public:
virtual ~HLUsageReportingInterface() = default;
virtual void ReportScheduler() = 0;
virtual void ReportSmartDashboard() = 0;
};
class HLUsageReporting {
private:
static HLUsageReportingInterface* impl;
public:
static void SetImplementation(HLUsageReportingInterface* i);
static void ReportScheduler();
static void ReportSmartDashboard();
};
} // namespace frc

View File

@@ -0,0 +1,50 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <stdint.h>
#include "SensorBase.h"
enum HAL_I2CPort : int32_t;
namespace frc {
/**
* I2C bus interface class.
*
* This class is intended to be used by sensor (and other I2C device) drivers.
* It probably should not be used directly.
*
*/
class I2C : SensorBase {
public:
enum Port { kOnboard = 0, kMXP };
I2C(Port port, int deviceAddress);
virtual ~I2C();
I2C(const I2C&) = delete;
I2C& operator=(const I2C&) = delete;
bool Transaction(uint8_t* dataToSend, int sendSize, uint8_t* dataReceived,
int receiveSize);
bool AddressOnly();
bool Write(int registerAddress, uint8_t data);
bool WriteBulk(uint8_t* data, int count);
bool Read(int registerAddress, int count, uint8_t* data);
bool ReadOnly(int count, uint8_t* buffer);
// void Broadcast(int registerAddress, uint8_t data);
bool VerifySensor(int registerAddress, int count, const uint8_t* expected);
private:
HAL_I2CPort m_port;
int m_deviceAddress;
};
} // namespace frc

View File

@@ -0,0 +1,20 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include "HLUsageReporting.h"
namespace frc {
class HardwareHLReporting : public HLUsageReportingInterface {
public:
virtual void ReportScheduler();
virtual void ReportSmartDashboard();
};
} // namespace frc

View File

@@ -0,0 +1,53 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include "AnalogTriggerType.h"
#include "HAL/Interrupts.h"
#include "SensorBase.h"
namespace frc {
class InterruptableSensorBase : public SensorBase {
public:
enum WaitResult {
kTimeout = 0x0,
kRisingEdge = 0x1,
kFallingEdge = 0x100,
kBoth = 0x101,
};
InterruptableSensorBase() = default;
virtual ~InterruptableSensorBase() = default;
virtual HAL_Handle GetPortHandleForRouting() const = 0;
virtual AnalogTriggerType GetAnalogTriggerTypeForRouting() const = 0;
virtual void RequestInterrupts(
HAL_InterruptHandlerFunction handler,
void* param); ///< Asynchronus handler version.
virtual void RequestInterrupts(); ///< Synchronus Wait version.
virtual void
CancelInterrupts(); ///< Free up the underlying chipobject functions.
virtual WaitResult WaitForInterrupt(
double timeout,
bool ignorePrevious = true); ///< Synchronus version.
virtual void
EnableInterrupts(); ///< Enable interrupts - after finishing setup.
virtual void DisableInterrupts(); ///< Disable, but don't deallocate.
virtual double ReadRisingTimestamp(); ///< Return the timestamp for the
/// rising interrupt that occurred.
virtual double ReadFallingTimestamp(); ///< Return the timestamp for the
/// falling interrupt that occurred.
virtual void SetUpSourceEdge(bool risingEdge, bool fallingEdge);
protected:
HAL_InterruptHandle m_interrupt = HAL_kInvalidHandle;
void AllocateInterrupts(bool watcher);
};
} // namespace frc

View File

@@ -0,0 +1,31 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include "IterativeRobotBase.h"
namespace frc {
/**
* IterativeRobot implements the IterativeRobotBase robot program framework.
*
* The IterativeRobot class is intended to be subclassed by a user creating a
* robot program.
*
* Periodic() functions from the base class are called each time a new packet is
* received from the driver station.
*/
class IterativeRobot : public IterativeRobotBase {
public:
IterativeRobot();
virtual ~IterativeRobot() = default;
void StartCompetition() override;
};
} // namespace frc

View File

@@ -0,0 +1,69 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include "RobotBase.h"
namespace frc {
/**
* IterativeRobotBase implements a specific type of robot program framework,
* extending the RobotBase class.
*
* The IterativeRobotBase class does not implement StartCompetition(), so it
* should not be used by teams directly.
*
* This class provides the following functions which are called by the main
* loop, StartCompetition(), at the appropriate times:
*
* RobotInit() -- provide for initialization at robot power-on
*
* Init() functions -- each of the following functions is called once when the
* appropriate mode is entered:
* - DisabledInit() -- called only when first disabled
* - AutonomousInit() -- called each and every time autonomous is entered from
* another mode
* - TeleopInit() -- called each and every time teleop is entered from
* another mode
* - TestInit() -- called each and every time test is entered from
* another mode
*
* Periodic() functions -- each of these functions is called on an interval:
* - RobotPeriodic()
* - DisabledPeriodic()
* - AutonomousPeriodic()
* - TeleopPeriodic()
* - TestPeriodic()
*/
class IterativeRobotBase : public RobotBase {
public:
virtual void RobotInit();
virtual void DisabledInit();
virtual void AutonomousInit();
virtual void TeleopInit();
virtual void TestInit();
virtual void RobotPeriodic();
virtual void DisabledPeriodic();
virtual void AutonomousPeriodic();
virtual void TeleopPeriodic();
virtual void TestPeriodic();
protected:
IterativeRobotBase();
virtual ~IterativeRobotBase() = default;
void LoopFunc();
private:
enum class Mode { kNone, kDisabled, kAutonomous, kTeleop, kTest };
Mode m_lastMode = Mode::kNone;
};
} // namespace frc

View File

@@ -0,0 +1,23 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include "PWMSpeedController.h"
namespace frc {
/**
* Luminary Micro / Vex Robotics Jaguar Speed Controller with PWM control
*/
class Jaguar : public PWMSpeedController {
public:
explicit Jaguar(int channel);
virtual ~Jaguar() = default;
};
} // namespace frc

View File

@@ -0,0 +1,88 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <stdint.h>
#include <memory>
#include <vector>
#include "ErrorBase.h"
#include "JoystickBase.h"
namespace frc {
class DriverStation;
/**
* Handle input from standard Joysticks connected to the Driver Station.
* This class handles standard input that comes from the Driver Station. Each
* time a value is requested the most recent value is returned. There is a
* single class instance for each joystick and the mapping of ports to hardware
* buttons depends on the code in the Driver Station.
*/
class Joystick : public JoystickBase, public ErrorBase {
public:
static const int kDefaultXAxis = 0;
static const int kDefaultYAxis = 1;
static const int kDefaultZAxis = 2;
static const int kDefaultTwistAxis = 2;
static const int kDefaultThrottleAxis = 3;
typedef enum {
kXAxis,
kYAxis,
kZAxis,
kTwistAxis,
kThrottleAxis,
kNumAxisTypes
} AxisType;
static const int kDefaultTriggerButton = 1;
static const int kDefaultTopButton = 2;
typedef enum { kTriggerButton, kTopButton, kNumButtonTypes } ButtonType;
explicit Joystick(int port);
Joystick(int port, int numAxisTypes, int numButtonTypes);
virtual ~Joystick() = default;
Joystick(const Joystick&) = delete;
Joystick& operator=(const Joystick&) = delete;
int GetAxisChannel(AxisType axis) const;
void SetAxisChannel(AxisType axis, int channel);
double GetX(JoystickHand hand = kRightHand) const override;
double GetY(JoystickHand hand = kRightHand) const override;
double GetZ(JoystickHand hand = kRightHand) const override;
double GetTwist() const override;
double GetThrottle() const override;
virtual double GetAxis(AxisType axis) const;
bool GetTrigger(JoystickHand hand = kRightHand) const override;
bool GetTop(JoystickHand hand = kRightHand) const override;
bool GetButton(ButtonType button) const;
static Joystick* GetStickForPort(int port);
virtual double GetMagnitude() const;
virtual double GetDirectionRadians() const;
virtual double GetDirectionDegrees() const;
int GetAxisType(int axis) const;
int GetAxisCount() const;
int GetButtonCount() const;
private:
DriverStation& m_ds;
std::vector<int> m_axes;
std::vector<int> m_buttons;
};
} // namespace frc

View File

@@ -0,0 +1,30 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include "GenericHID.h"
namespace frc {
/**
* Joystick Interface.
*/
class JoystickBase : public GenericHID {
public:
explicit JoystickBase(int port);
virtual ~JoystickBase() = default;
virtual double GetZ(JoystickHand hand = kRightHand) const = 0;
virtual double GetTwist() const = 0;
virtual double GetThrottle() const = 0;
virtual bool GetTrigger(JoystickHand hand = kRightHand) const = 0;
virtual bool GetTop(JoystickHand hand = kRightHand) const = 0;
};
} // namespace frc

View File

@@ -0,0 +1,87 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2012-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <map>
#include <memory>
#include <string>
#include <vector>
#include "Commands/Scheduler.h"
#include "LiveWindow/LiveWindowSendable.h"
#include "tables/ITable.h"
namespace frc {
struct LiveWindowComponent {
std::string subsystem;
std::string name;
bool isSensor = false;
LiveWindowComponent() = default;
LiveWindowComponent(std::string subsystem, std::string name, bool isSensor) {
this->subsystem = subsystem;
this->name = name;
this->isSensor = isSensor;
}
};
/**
* The LiveWindow class is the public interface for putting sensors and
* actuators
* on the LiveWindow.
*/
class LiveWindow {
public:
static LiveWindow* GetInstance();
void Run();
void AddSensor(const std::string& subsystem, const std::string& name,
LiveWindowSendable* component);
void AddSensor(const std::string& subsystem, const std::string& name,
LiveWindowSendable& component);
void AddSensor(const std::string& subsystem, const std::string& name,
std::shared_ptr<LiveWindowSendable> component);
void AddActuator(const std::string& subsystem, const std::string& name,
LiveWindowSendable* component);
void AddActuator(const std::string& subsystem, const std::string& name,
LiveWindowSendable& component);
void AddActuator(const std::string& subsystem, const std::string& name,
std::shared_ptr<LiveWindowSendable> component);
void AddSensor(std::string type, int channel, LiveWindowSendable* component);
void AddActuator(std::string type, int channel,
LiveWindowSendable* component);
void AddActuator(std::string type, int module, int channel,
LiveWindowSendable* component);
bool IsEnabled() const { return m_enabled; }
void SetEnabled(bool enabled);
protected:
LiveWindow();
virtual ~LiveWindow() = default;
private:
void UpdateValues();
void Initialize();
void InitializeLiveWindowComponents();
std::vector<std::shared_ptr<LiveWindowSendable>> m_sensors;
std::map<std::shared_ptr<LiveWindowSendable>, LiveWindowComponent>
m_components;
std::shared_ptr<ITable> m_liveWindowTable;
std::shared_ptr<ITable> m_statusTable;
Scheduler* m_scheduler;
bool m_enabled = false;
bool m_firstTime = true;
};
} // namespace frc

View File

@@ -0,0 +1,38 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2012-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include "SmartDashboard/Sendable.h"
namespace frc {
/**
* Live Window Sendable is a special type of object sendable to the live window.
*/
class LiveWindowSendable : public Sendable {
public:
/**
* Update the table for this sendable object with the latest
* values.
*/
virtual void UpdateTable() = 0;
/**
* Start having this sendable object automatically respond to
* value changes reflect the value on the table.
*/
virtual void StartLiveWindowMode() = 0;
/**
* Stop having this sendable object automatically respond to value
* changes.
*/
virtual void StopLiveWindowMode() = 0;
};
} // namespace frc

View File

@@ -0,0 +1,23 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2012-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <memory>
#include "tables/ITable.h"
#include "tables/ITableListener.h"
namespace frc {
class LiveWindowStatusListener : public ITableListener {
public:
virtual void ValueChanged(ITable* source, llvm::StringRef key,
std::shared_ptr<nt::Value> value, bool isNew);
};
} // namespace frc

View File

@@ -0,0 +1,27 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#define DEFAULT_SAFETY_EXPIRATION 0.1
#include "llvm/raw_ostream.h"
namespace frc {
class MotorSafety {
public:
virtual void SetExpiration(double timeout) = 0;
virtual double GetExpiration() const = 0;
virtual bool IsAlive() const = 0;
virtual void StopMotor() = 0;
virtual void SetSafetyEnabled(bool enabled) = 0;
virtual bool IsSafetyEnabled() const = 0;
virtual void GetDescription(llvm::raw_ostream& desc) const = 0;
};
} // namespace frc

View File

@@ -0,0 +1,49 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <set>
#include "ErrorBase.h"
#include "HAL/cpp/priority_mutex.h"
namespace frc {
class MotorSafety;
class MotorSafetyHelper : public ErrorBase {
public:
explicit MotorSafetyHelper(MotorSafety* safeObject);
~MotorSafetyHelper();
void Feed();
void SetExpiration(double expirationTime);
double GetExpiration() const;
bool IsAlive() const;
void Check();
void SetSafetyEnabled(bool enabled);
bool IsSafetyEnabled() const;
static void CheckMotors();
private:
// the expiration time for this object
double m_expiration;
// true if motor safety is enabled for this motor
bool m_enabled;
// the FPGA clock value when this motor has expired
double m_stopTime;
// protect accesses to the state for this object
mutable hal::priority_recursive_mutex m_syncMutex;
// the object that is using the helper
MotorSafety* m_safeObject;
// List of all existing MotorSafetyHelper objects.
static std::set<MotorSafetyHelper*> m_helperList;
// protect accesses to the list of helpers
static hal::priority_recursive_mutex m_listMutex;
};
} // namespace frc

View File

@@ -0,0 +1,64 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <stdint.h>
#include <atomic>
#include <functional>
#include <utility>
#include "ErrorBase.h"
#include "HAL/Notifier.h"
#include "HAL/cpp/priority_mutex.h"
namespace frc {
typedef std::function<void()> TimerEventHandler;
class Notifier : public ErrorBase {
public:
explicit Notifier(TimerEventHandler handler);
template <typename Callable, typename Arg, typename... Args>
Notifier(Callable&& f, Arg&& arg, Args&&... args)
: Notifier(std::bind(std::forward<Callable>(f), std::forward<Arg>(arg),
std::forward<Args>(args)...)) {}
virtual ~Notifier();
Notifier(const Notifier&) = delete;
Notifier& operator=(const Notifier&) = delete;
void StartSingle(double delay);
void StartPeriodic(double period);
void Stop();
private:
// update the HAL alarm
void UpdateAlarm();
// HAL callback
static void Notify(uint64_t currentTimeInt, HAL_NotifierHandle handle);
// used to constrain execution between destructors and callback
static hal::priority_mutex m_destructorMutex;
// held while updating process information
hal::priority_mutex m_processMutex;
// HAL handle, atomic for proper destruction
std::atomic<HAL_NotifierHandle> m_notifier{0};
// address of the handler
TimerEventHandler m_handler;
// the absolute expiration time
double m_expirationTime = 0;
// the relative time (either periodic or single)
double m_period = 0;
// true if this is a periodic event
bool m_periodic = false;
};
} // namespace frc

View File

@@ -0,0 +1,153 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <atomic>
#include <memory>
#include <queue>
#include <string>
#include "Base.h"
#include "Controller.h"
#include "HAL/cpp/priority_mutex.h"
#include "LiveWindow/LiveWindow.h"
#include "Notifier.h"
#include "PIDInterface.h"
#include "PIDSource.h"
#include "Timer.h"
namespace frc {
class PIDOutput;
/**
* Class implements a PID Control Loop.
*
* Creates a separate thread which reads the given PIDSource and takes
* care of the integral calculations, as well as writing the given PIDOutput.
*
* This feedback controller runs in discrete time, so time deltas are not used
* in the integral and derivative calculations. Therefore, the sample rate
* affects the controller's behavior for a given set of PID constants.
*/
class PIDController : public LiveWindowSendable,
public PIDInterface,
public ITableListener {
public:
PIDController(double p, double i, double d, PIDSource* source,
PIDOutput* output, double period = 0.05);
PIDController(double p, double i, double d, double f, PIDSource* source,
PIDOutput* output, double period = 0.05);
virtual ~PIDController();
PIDController(const PIDController&) = delete;
PIDController& operator=(const PIDController) = delete;
virtual double Get() const;
virtual void SetContinuous(bool continuous = true);
virtual void SetInputRange(double minimumInput, double maximumInput);
virtual void SetOutputRange(double minimumOutput, double maximumOutput);
void SetPID(double p, double i, double d) override;
virtual void SetPID(double p, double i, double d, double f);
double GetP() const override;
double GetI() const override;
double GetD() const override;
virtual double GetF() const;
void SetSetpoint(double setpoint) override;
double GetSetpoint() const override;
double GetDeltaSetpoint() const;
virtual double GetError() const;
virtual double GetAvgError() const;
virtual void SetPIDSourceType(PIDSourceType pidSource);
virtual PIDSourceType GetPIDSourceType() const;
virtual void SetTolerance(double percent);
virtual void SetAbsoluteTolerance(double absValue);
virtual void SetPercentTolerance(double percentValue);
virtual void SetToleranceBuffer(int buf = 1);
virtual bool OnTarget() const;
void Enable() override;
void Disable() override;
bool IsEnabled() const override;
void Reset() override;
void InitTable(std::shared_ptr<ITable> subtable) override;
protected:
PIDSource* m_pidInput;
PIDOutput* m_pidOutput;
std::shared_ptr<ITable> m_table;
virtual void Calculate();
virtual double CalculateFeedForward();
double GetContinuousError(double error) const;
private:
// factor for "proportional" control
double m_P;
// factor for "integral" control
double m_I;
// factor for "derivative" control
double m_D;
// factor for "feed forward" control
double m_F;
// |maximum output|
double m_maximumOutput = 1.0;
// |minimum output|
double m_minimumOutput = -1.0;
// maximum input - limit setpoint to this
double m_maximumInput = 0;
// minimum input - limit setpoint to this
double m_minimumInput = 0;
// do the endpoints wrap around? eg. Absolute encoder
bool m_continuous = false;
// is the pid controller enabled
bool m_enabled = false;
// the prior error (used to compute velocity)
double m_prevError = 0;
// the sum of the errors for use in the integral calc
double m_totalError = 0;
enum {
kAbsoluteTolerance,
kPercentTolerance,
kNoTolerance
} m_toleranceType = kNoTolerance;
// the percetage or absolute error that is considered on target.
double m_tolerance = 0.05;
double m_setpoint = 0;
double m_prevSetpoint = 0;
double m_error = 0;
double m_result = 0;
double m_period;
// Length of buffer for averaging for tolerances.
std::atomic<unsigned> m_bufLength{1};
std::queue<double> m_buf;
double m_bufTotal = 0;
mutable hal::priority_recursive_mutex m_mutex;
std::unique_ptr<Notifier> m_controlLoop;
Timer m_setpointTimer;
std::shared_ptr<ITable> GetTable() const override;
std::string GetSmartDashboardType() const override;
void ValueChanged(ITable* source, llvm::StringRef key,
std::shared_ptr<nt::Value> value, bool isNew) override;
void UpdateTable() override;
void StartLiveWindowMode() override;
void StopLiveWindowMode() override;
};
} // namespace frc

View File

@@ -0,0 +1,32 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include "Base.h"
#include "Controller.h"
#include "LiveWindow/LiveWindow.h"
namespace frc {
class PIDInterface : public Controller {
virtual void SetPID(double p, double i, double d) = 0;
virtual double GetP() const = 0;
virtual double GetI() const = 0;
virtual double GetD() const = 0;
virtual void SetSetpoint(double setpoint) = 0;
virtual double GetSetpoint() const = 0;
virtual void Enable() = 0;
virtual void Disable() = 0;
virtual bool IsEnabled() const = 0;
virtual void Reset() = 0;
};
} // namespace frc

View File

@@ -0,0 +1,25 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include "Base.h"
namespace frc {
/**
* PIDOutput interface is a generic output for the PID class.
* PWMs use this class.
* Users implement this interface to allow for a PIDController to
* read directly from the inputs.
*/
class PIDOutput {
public:
virtual void PIDWrite(double output) = 0;
};
} // namespace frc

View File

@@ -0,0 +1,29 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
namespace frc {
enum class PIDSourceType { kDisplacement, kRate };
/**
* PIDSource interface is a generic sensor source for the PID class.
* All sensors that can be used with the PID class will implement the PIDSource
* that returns a standard value that will be used in the PID code.
*/
class PIDSource {
public:
virtual void SetPIDSourceType(PIDSourceType pidSource);
PIDSourceType GetPIDSourceType() const;
virtual double PIDGet() = 0;
protected:
PIDSourceType m_pidSource = PIDSourceType::kDisplacement;
};
} // namespace frc

View File

@@ -0,0 +1,86 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <stdint.h>
#include <memory>
#include <string>
#include "HAL/Types.h"
#include "LiveWindow/LiveWindowSendable.h"
#include "SensorBase.h"
#include "tables/ITableListener.h"
namespace frc {
/**
* Class implements the PWM generation in the FPGA.
*
* The values supplied as arguments for PWM outputs range from -1.0 to 1.0. They
* are mapped to the hardware dependent values, in this case 0-2000 for the
* FPGA. Changes are immediately sent to the FPGA, and the update occurs at the
* next FPGA cycle. There is no delay.
*
* As of revision 0.1.10 of the FPGA, the FPGA interprets the 0-2000 values as
* follows:
* - 2000 = maximum pulse width
* - 1999 to 1001 = linear scaling from "full forward" to "center"
* - 1000 = center value
* - 999 to 2 = linear scaling from "center" to "full reverse"
* - 1 = minimum pulse width (currently .5ms)
* - 0 = disabled (i.e. PWM output is held low)
*/
class PWM : public SensorBase,
public ITableListener,
public LiveWindowSendable {
public:
enum PeriodMultiplier {
kPeriodMultiplier_1X = 1,
kPeriodMultiplier_2X = 2,
kPeriodMultiplier_4X = 4
};
explicit PWM(int channel);
virtual ~PWM();
virtual void SetRaw(uint16_t value);
virtual uint16_t GetRaw() const;
virtual void SetPosition(double pos);
virtual double GetPosition() const;
virtual void SetSpeed(double speed);
virtual double GetSpeed() const;
virtual void SetDisabled();
void SetPeriodMultiplier(PeriodMultiplier mult);
void SetZeroLatch();
void EnableDeadbandElimination(bool eliminateDeadband);
void SetBounds(double max, double deadbandMax, double center,
double deadbandMin, double min);
void SetRawBounds(int max, int deadbandMax, int center, int deadbandMin,
int min);
void GetRawBounds(int32_t* max, int32_t* deadbandMax, int32_t* center,
int32_t* deadbandMin, int32_t* min);
int GetChannel() const { return m_channel; }
protected:
void ValueChanged(ITable* source, llvm::StringRef key,
std::shared_ptr<nt::Value> value, bool isNew) override;
void UpdateTable() override;
void StartLiveWindowMode() override;
void StopLiveWindowMode() override;
std::string GetSmartDashboardType() const override;
void InitTable(std::shared_ptr<ITable> subTable) override;
std::shared_ptr<ITable> GetTable() const override;
std::shared_ptr<ITable> m_table;
private:
int m_channel;
HAL_DigitalHandle m_handle;
};
} // namespace frc

View File

@@ -0,0 +1,37 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include "SafePWM.h"
#include "SpeedController.h"
namespace frc {
/**
* Common base class for all PWM Speed Controllers
*/
class PWMSpeedController : public SafePWM, public SpeedController {
public:
virtual ~PWMSpeedController() = default;
void Set(double value) override;
double Get() const override;
void SetInverted(bool isInverted) override;
bool GetInverted() const override;
void Disable() override;
void StopMotor() override;
void PIDWrite(double output) override;
protected:
explicit PWMSpeedController(int channel);
private:
bool m_isInverted = false;
};
} // namespace frc

View File

@@ -0,0 +1,48 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2014-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <memory>
#include <string>
#include "LiveWindow/LiveWindowSendable.h"
#include "SensorBase.h"
namespace frc {
/**
* Class for getting voltage, current, temperature, power and energy from the
* CAN PDP.
*/
class PowerDistributionPanel : public SensorBase, public LiveWindowSendable {
public:
PowerDistributionPanel();
explicit PowerDistributionPanel(int module);
double GetVoltage() const;
double GetTemperature() const;
double GetCurrent(int channel) const;
double GetTotalCurrent() const;
double GetTotalPower() const;
double GetTotalEnergy() const;
void ResetTotalEnergy();
void ClearStickyFaults();
void UpdateTable() override;
void StartLiveWindowMode() override;
void StopLiveWindowMode() override;
std::string GetSmartDashboardType() const override;
void InitTable(std::shared_ptr<ITable> subTable) override;
std::shared_ptr<ITable> GetTable() const override;
private:
std::shared_ptr<ITable> m_table;
int m_module;
};
} // namespace frc

View File

@@ -0,0 +1,73 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <stdint.h>
#include <memory>
#include <string>
#include <vector>
#include "ErrorBase.h"
#include "networktables/NetworkTable.h"
#include "tables/ITableListener.h"
namespace frc {
/**
* The preferences class provides a relatively simple way to save important
* values to the roboRIO to access the next time the roboRIO is booted.
*
* <p>This class loads and saves from a file inside the roboRIO. The user can
* not access the file directly, but may modify values at specific fields which
* will then be automatically periodically saved to the file by the NetworkTable
* server.</p>
*
* <p>This class is thread safe.</p>
*
* <p>This will also interact with {@link NetworkTable} by creating a table
* called "Preferences" with all the key-value pairs.</p>
*/
class Preferences : public ErrorBase {
public:
static Preferences* GetInstance();
std::vector<std::string> GetKeys();
std::string GetString(llvm::StringRef key, llvm::StringRef defaultValue = "");
int GetInt(llvm::StringRef key, int defaultValue = 0);
double GetDouble(llvm::StringRef key, double defaultValue = 0.0);
float GetFloat(llvm::StringRef key, float defaultValue = 0.0);
bool GetBoolean(llvm::StringRef key, bool defaultValue = false);
int64_t GetLong(llvm::StringRef key, int64_t defaultValue = 0);
void PutString(llvm::StringRef key, llvm::StringRef value);
void PutInt(llvm::StringRef key, int value);
void PutDouble(llvm::StringRef key, double value);
void PutFloat(llvm::StringRef key, float value);
void PutBoolean(llvm::StringRef key, bool value);
void PutLong(llvm::StringRef key, int64_t value);
bool ContainsKey(llvm::StringRef key);
void Remove(llvm::StringRef key);
protected:
Preferences();
virtual ~Preferences() = default;
private:
std::shared_ptr<ITable> m_table;
class Listener : public ITableListener {
public:
void ValueChanged(ITable* source, llvm::StringRef key,
std::shared_ptr<nt::Value> value, bool isNew) override;
void ValueChangedEx(ITable* source, llvm::StringRef key,
std::shared_ptr<nt::Value> value,
uint32_t flags) override;
};
Listener m_listener;
};
} // namespace frc

View File

@@ -0,0 +1,80 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <memory>
#include <string>
#include "HAL/Types.h"
#include "LiveWindow/LiveWindowSendable.h"
#include "MotorSafety.h"
#include "SensorBase.h"
#include "llvm/raw_ostream.h"
#include "tables/ITable.h"
#include "tables/ITableListener.h"
namespace frc {
class MotorSafetyHelper;
/**
* Class for Spike style relay outputs.
* Relays are intended to be connected to spikes or similar relays. The relay
* channels controls a pair of pins that are either both off, one on, the other
* on, or both on. This translates into two spike outputs at 0v, one at 12v and
* one at 0v, one at 0v and the other at 12v, or two spike outputs at 12V. This
* allows off, full forward, or full reverse control of motors without variable
* speed. It also allows the two channels (forward and reverse) to be used
* independently for something that does not care about voltage polarity (like
* a solenoid).
*/
class Relay : public MotorSafety,
public SensorBase,
public ITableListener,
public LiveWindowSendable {
public:
enum Value { kOff, kOn, kForward, kReverse };
enum Direction { kBothDirections, kForwardOnly, kReverseOnly };
explicit Relay(int channel, Direction direction = kBothDirections);
virtual ~Relay();
void Set(Value value);
Value Get() const;
int GetChannel() const;
void SetExpiration(double timeout) override;
double GetExpiration() const override;
bool IsAlive() const override;
void StopMotor() override;
bool IsSafetyEnabled() const override;
void SetSafetyEnabled(bool enabled) override;
void GetDescription(llvm::raw_ostream& desc) const override;
void ValueChanged(ITable* source, llvm::StringRef key,
std::shared_ptr<nt::Value> value, bool isNew) override;
void UpdateTable() override;
void StartLiveWindowMode() override;
void StopLiveWindowMode() override;
std::string GetSmartDashboardType() const override;
void InitTable(std::shared_ptr<ITable> subTable) override;
std::shared_ptr<ITable> GetTable() const override;
std::shared_ptr<ITable> m_table;
private:
int m_channel;
Direction m_direction;
HAL_RelayHandle m_forwardHandle = HAL_kInvalidHandle;
HAL_RelayHandle m_reverseHandle = HAL_kInvalidHandle;
std::unique_ptr<MotorSafetyHelper> m_safetyHelper;
};
} // namespace frc

View File

@@ -0,0 +1,51 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <stdint.h>
#include <memory>
#include <string>
#include <vector>
#include "ErrorBase.h"
#include "HAL/cpp/priority_mutex.h"
namespace frc {
/**
* The Resource class is a convenient way to track allocated resources.
* It tracks them as indicies in the range [0 .. elements - 1].
* E.g. the library uses this to track hardware channel allocation.
*
* The Resource class does not allocate the hardware channels or other
* resources; it just tracks which indices were marked in use by
* Allocate and not yet freed by Free.
*/
class Resource : public ErrorBase {
public:
virtual ~Resource() = default;
Resource(const Resource&) = delete;
Resource& operator=(const Resource&) = delete;
static void CreateResourceObject(std::unique_ptr<Resource>& r,
uint32_t elements);
explicit Resource(uint32_t size);
uint32_t Allocate(const std::string& resourceDesc);
uint32_t Allocate(uint32_t index, const std::string& resourceDesc);
void Free(uint32_t index);
private:
std::vector<bool> m_isAllocated;
hal::priority_recursive_mutex m_allocateLock;
static hal::priority_recursive_mutex m_createLock;
};
} // namespace frc

View File

@@ -0,0 +1,65 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <thread>
#include "Base.h"
#include "HAL/HAL.h"
#include "llvm/raw_ostream.h"
namespace frc {
class DriverStation;
#define START_ROBOT_CLASS(_ClassName_) \
int main() { \
if (!HAL_Initialize(500, 0)) { \
llvm::errs() << "FATAL ERROR: HAL could not be initialized\n"; \
return -1; \
} \
HAL_Report(HALUsageReporting::kResourceType_Language, \
HALUsageReporting::kLanguage_CPlusPlus); \
llvm::outs() << "\n********** Robot program starting **********\n"; \
static _ClassName_ robot; \
robot.StartCompetition(); \
}
/**
* Implement a Robot Program framework.
* The RobotBase class is intended to be subclassed by a user creating a robot
* program. Overridden Autonomous() and OperatorControl() methods are called at
* the appropriate time as the match proceeds. In the current implementation,
* the Autonomous code will run to completion before the OperatorControl code
* could start. In the future the Autonomous code might be spawned as a task,
* then killed at the end of the Autonomous period.
*/
class RobotBase {
public:
bool IsEnabled() const;
bool IsDisabled() const;
bool IsAutonomous() const;
bool IsOperatorControl() const;
bool IsTest() const;
bool IsNewDataAvailable() const;
static std::thread::id GetThreadId();
virtual void StartCompetition() = 0;
protected:
RobotBase();
virtual ~RobotBase() = default;
RobotBase(const RobotBase&) = delete;
RobotBase& operator=(const RobotBase&) = delete;
DriverStation& m_ds;
static std::thread::id m_threadId;
};
} // namespace frc

View File

@@ -0,0 +1,125 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <memory>
#include "ErrorBase.h"
#include "MotorSafety.h"
#include "MotorSafetyHelper.h"
#include "llvm/raw_ostream.h"
namespace frc {
class SpeedController;
class GenericHID;
/**
* Utility class for handling Robot drive based on a definition of the motor
* configuration.
* The robot drive class handles basic driving for a robot. Currently, 2 and 4
* motor tank and mecanum drive trains are supported. In the future other drive
* types like swerve might be implemented. Motor channel numbers are passed
* supplied on creation of the class. Those are used for either the Drive
* function (intended for hand created drive code, such as autonomous) or with
* the Tank/Arcade functions intended to be used for Operator Control driving.
*/
class RobotDrive : public MotorSafety, public ErrorBase {
public:
enum MotorType {
kFrontLeftMotor = 0,
kFrontRightMotor = 1,
kRearLeftMotor = 2,
kRearRightMotor = 3
};
RobotDrive(int leftMotorChannel, int rightMotorChannel);
RobotDrive(int frontLeftMotorChannel, int rearLeftMotorChannel,
int frontRightMotorChannel, int rearRightMotorChannel);
RobotDrive(SpeedController* leftMotor, SpeedController* rightMotor);
RobotDrive(SpeedController& leftMotor, SpeedController& rightMotor);
RobotDrive(std::shared_ptr<SpeedController> leftMotor,
std::shared_ptr<SpeedController> rightMotor);
RobotDrive(SpeedController* frontLeftMotor, SpeedController* rearLeftMotor,
SpeedController* frontRightMotor, SpeedController* rearRightMotor);
RobotDrive(SpeedController& frontLeftMotor, SpeedController& rearLeftMotor,
SpeedController& frontRightMotor, SpeedController& rearRightMotor);
RobotDrive(std::shared_ptr<SpeedController> frontLeftMotor,
std::shared_ptr<SpeedController> rearLeftMotor,
std::shared_ptr<SpeedController> frontRightMotor,
std::shared_ptr<SpeedController> rearRightMotor);
virtual ~RobotDrive() = default;
RobotDrive(const RobotDrive&) = delete;
RobotDrive& operator=(const RobotDrive&) = delete;
void Drive(double outputMagnitude, double curve);
void TankDrive(GenericHID* leftStick, GenericHID* rightStick,
bool squaredInputs = true);
void TankDrive(GenericHID& leftStick, GenericHID& rightStick,
bool squaredInputs = true);
void TankDrive(GenericHID* leftStick, int leftAxis, GenericHID* rightStick,
int rightAxis, bool squaredInputs = true);
void TankDrive(GenericHID& leftStick, int leftAxis, GenericHID& rightStick,
int rightAxis, bool squaredInputs = true);
void TankDrive(double leftValue, double rightValue,
bool squaredInputs = true);
void ArcadeDrive(GenericHID* stick, bool squaredInputs = true);
void ArcadeDrive(GenericHID& stick, bool squaredInputs = true);
void ArcadeDrive(GenericHID* moveStick, int moveChannel,
GenericHID* rotateStick, int rotateChannel,
bool squaredInputs = true);
void ArcadeDrive(GenericHID& moveStick, int moveChannel,
GenericHID& rotateStick, int rotateChannel,
bool squaredInputs = true);
void ArcadeDrive(double moveValue, double rotateValue,
bool squaredInputs = true);
void MecanumDrive_Cartesian(double x, double y, double rotation,
double gyroAngle = 0.0);
void MecanumDrive_Polar(double magnitude, double direction, double rotation);
void HolonomicDrive(double magnitude, double direction, double rotation);
virtual void SetLeftRightMotorOutputs(double leftOutput, double rightOutput);
void SetInvertedMotor(MotorType motor, bool isInverted);
void SetSensitivity(double sensitivity);
void SetMaxOutput(double maxOutput);
void SetExpiration(double timeout) override;
double GetExpiration() const override;
bool IsAlive() const override;
void StopMotor() override;
bool IsSafetyEnabled() const override;
void SetSafetyEnabled(bool enabled) override;
void GetDescription(llvm::raw_ostream& desc) const override;
protected:
void InitRobotDrive();
double Limit(double number);
void Normalize(double* wheelSpeeds);
void RotateVector(double& x, double& y, double angle);
static const int kMaxNumberOfMotors = 4;
double m_sensitivity = 0.5;
double m_maxOutput = 1.0;
std::shared_ptr<SpeedController> m_frontLeftMotor;
std::shared_ptr<SpeedController> m_frontRightMotor;
std::shared_ptr<SpeedController> m_rearLeftMotor;
std::shared_ptr<SpeedController> m_rearRightMotor;
std::unique_ptr<MotorSafetyHelper> m_safetyHelper;
private:
int GetNumMotors() {
int motors = 0;
if (m_frontLeftMotor) motors++;
if (m_frontRightMotor) motors++;
if (m_rearLeftMotor) motors++;
if (m_rearRightMotor) motors++;
return motors;
}
};
} // namespace frc

View File

@@ -0,0 +1,38 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <memory>
namespace frc {
class RobotStateInterface {
public:
virtual ~RobotStateInterface() = default;
virtual bool IsDisabled() const = 0;
virtual bool IsEnabled() const = 0;
virtual bool IsOperatorControl() const = 0;
virtual bool IsAutonomous() const = 0;
virtual bool IsTest() const = 0;
};
class RobotState {
private:
static std::shared_ptr<RobotStateInterface> impl;
public:
static void SetImplementation(RobotStateInterface& i);
static void SetImplementation(std::shared_ptr<RobotStateInterface> i);
static bool IsDisabled();
static bool IsEnabled();
static bool IsOperatorControl();
static bool IsAutonomous();
static bool IsTest();
};
} // namespace frc

View File

@@ -0,0 +1,23 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include "PWMSpeedController.h"
namespace frc {
/**
* Mindsensors SD540 Speed Controller
*/
class SD540 : public PWMSpeedController {
public:
explicit SD540(int channel);
virtual ~SD540() = default;
};
} // namespace frc

View File

@@ -0,0 +1,78 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <stdint.h>
#include "SensorBase.h"
enum HAL_SPIPort : int32_t;
namespace frc {
class DigitalOutput;
class DigitalInput;
/**
* SPI bus interface class.
*
* This class is intended to be used by sensor (and other SPI device) drivers.
* It probably should not be used directly.
*
*/
class SPI : public SensorBase {
public:
enum Port { kOnboardCS0 = 0, kOnboardCS1, kOnboardCS2, kOnboardCS3, kMXP };
explicit SPI(Port port);
virtual ~SPI();
SPI(const SPI&) = delete;
SPI& operator=(const SPI&) = delete;
void SetClockRate(double hz);
void SetMSBFirst();
void SetLSBFirst();
void SetSampleDataOnFalling();
void SetSampleDataOnRising();
void SetClockActiveLow();
void SetClockActiveHigh();
void SetChipSelectActiveHigh();
void SetChipSelectActiveLow();
virtual int Write(uint8_t* data, int size);
virtual int Read(bool initiate, uint8_t* dataReceived, int size);
virtual int Transaction(uint8_t* dataToSend, uint8_t* dataReceived, int size);
void InitAccumulator(double period, int cmd, int xfer_size, int valid_mask,
int valid_value, int data_shift, int data_size,
bool is_signed, bool big_endian);
void FreeAccumulator();
void ResetAccumulator();
void SetAccumulatorCenter(int center);
void SetAccumulatorDeadband(int deadband);
int GetAccumulatorLastValue() const;
int64_t GetAccumulatorValue() const;
int64_t GetAccumulatorCount() const;
double GetAccumulatorAverage() const;
void GetAccumulatorOutput(int64_t& value, int64_t& count) const;
protected:
HAL_SPIPort m_port;
bool m_msbFirst = false; // default little-endian
bool m_sampleOnTrailing = false; // default data updated on falling edge
bool m_clk_idle_high = false; // default clock active high
private:
void Init();
};
} // namespace frc

View File

@@ -0,0 +1,45 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <memory>
#include "MotorSafety.h"
#include "MotorSafetyHelper.h"
#include "PWM.h"
#include "llvm/raw_ostream.h"
namespace frc {
/**
* A safe version of the PWM class.
* It is safe because it implements the MotorSafety interface that provides
* timeouts in the event that the motor value is not updated before the
* expiration time. This delegates the actual work to a MotorSafetyHelper
* object that is used for all objects that implement MotorSafety.
*/
class SafePWM : public PWM, public MotorSafety {
public:
explicit SafePWM(int channel);
virtual ~SafePWM() = default;
void SetExpiration(double timeout);
double GetExpiration() const;
bool IsAlive() const;
void StopMotor();
bool IsSafetyEnabled() const;
void SetSafetyEnabled(bool enabled);
void GetDescription(llvm::raw_ostream& desc) const;
virtual void SetSpeed(double speed);
private:
std::unique_ptr<MotorSafetyHelper> m_safetyHelper;
};
} // namespace frc

View File

@@ -0,0 +1,33 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include "RobotBase.h"
namespace frc {
class SampleRobot : public RobotBase {
public:
void StartCompetition() override;
virtual void RobotInit();
virtual void Disabled();
virtual void Autonomous();
virtual void OperatorControl();
virtual void Test();
virtual void RobotMain();
protected:
SampleRobot();
virtual ~SampleRobot() = default;
private:
bool m_robotMainOverridden = true;
};
} // namespace frc

View File

@@ -0,0 +1,49 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include "Base.h"
#include "ErrorBase.h"
namespace frc {
/**
* Base class for all sensors.
* Stores most recent status information as well as containing utility functions
* for checking channels and error processing.
*/
class SensorBase : public ErrorBase {
public:
SensorBase() = default;
virtual ~SensorBase() = default;
SensorBase(const SensorBase&) = delete;
SensorBase& operator=(const SensorBase&) = delete;
static int GetDefaultSolenoidModule() { return 0; }
static bool CheckSolenoidModule(int moduleNumber);
static bool CheckDigitalChannel(int channel);
static bool CheckRelayChannel(int channel);
static bool CheckPWMChannel(int channel);
static bool CheckAnalogInputChannel(int channel);
static bool CheckAnalogOutputChannel(int channel);
static bool CheckSolenoidChannel(int channel);
static bool CheckPDPChannel(int channel);
static const int kDigitalChannels;
static const int kAnalogInputs;
static const int kAnalogOutputs;
static const int kSolenoidChannels;
static const int kSolenoidModules;
static const int kPwmChannels;
static const int kRelayChannels;
static const int kPDPChannels;
};
} // namespace frc

View File

@@ -0,0 +1,80 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <string>
#include "ErrorBase.h"
#include "llvm/StringRef.h"
namespace frc {
/**
* Driver for the RS-232 serial port on the roboRIO.
*
* The current implementation uses the VISA formatted I/O mode. This means that
* all traffic goes through the fomatted buffers. This allows the intermingled
* use of Printf(), Scanf(), and the raw buffer accessors Read() and Write().
*
* More information can be found in the NI-VISA User Manual here:
* http://www.ni.com/pdf/manuals/370423a.pdf
* and the NI-VISA Programmer's Reference Manual here:
* http://www.ni.com/pdf/manuals/370132c.pdf
*/
class SerialPort : public ErrorBase {
public:
enum Parity {
kParity_None = 0,
kParity_Odd = 1,
kParity_Even = 2,
kParity_Mark = 3,
kParity_Space = 4
};
enum StopBits {
kStopBits_One = 10,
kStopBits_OnePointFive = 15,
kStopBits_Two = 20
};
enum FlowControl {
kFlowControl_None = 0,
kFlowControl_XonXoff = 1,
kFlowControl_RtsCts = 2,
kFlowControl_DtrDsr = 4
};
enum WriteBufferMode { kFlushOnAccess = 1, kFlushWhenFull = 2 };
enum Port { kOnboard = 0, kMXP = 1, kUSB = 2, kUSB1 = 2, kUSB2 = 3 };
SerialPort(int baudRate, Port port = kOnboard, int dataBits = 8,
Parity parity = kParity_None, StopBits stopBits = kStopBits_One);
~SerialPort();
SerialPort(const SerialPort&) = delete;
SerialPort& operator=(const SerialPort&) = delete;
void SetFlowControl(FlowControl flowControl);
void EnableTermination(char terminator = '\n');
void DisableTermination();
int GetBytesReceived();
int Read(char* buffer, int count);
int Write(const char* buffer, int count);
int Write(llvm::StringRef buffer);
void SetTimeout(double timeout);
void SetReadBufferSize(int size);
void SetWriteBufferSize(int size);
void SetWriteBufferMode(WriteBufferMode mode);
void Flush();
void Reset();
private:
int m_resourceManagerHandle = 0;
int m_portHandle = 0;
bool m_consoleModeEnabled = false;
int m_port;
};
} // namespace frc

View File

@@ -0,0 +1,58 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <memory>
#include <string>
#include "SafePWM.h"
#include "SpeedController.h"
namespace frc {
/**
* Standard hobby style servo.
*
* The range parameters default to the appropriate values for the Hitec HS-322HD
* servo provided
* in the FIRST Kit of Parts in 2008.
*/
class Servo : public SafePWM {
public:
explicit Servo(int channel);
virtual ~Servo();
void Set(double value);
void SetOffline();
double Get() const;
void SetAngle(double angle);
double GetAngle() const;
static double GetMaxAngle() { return kMaxServoAngle; }
static double GetMinAngle() { return kMinServoAngle; }
void ValueChanged(ITable* source, llvm::StringRef key,
std::shared_ptr<nt::Value> value, bool isNew) override;
void UpdateTable() override;
void StartLiveWindowMode() override;
void StopLiveWindowMode() override;
std::string GetSmartDashboardType() const override;
void InitTable(std::shared_ptr<ITable> subTable) override;
std::shared_ptr<ITable> GetTable() const override;
std::shared_ptr<ITable> m_table;
private:
double GetServoAngleRange() const { return kMaxServoAngle - kMinServoAngle; }
static constexpr double kMaxServoAngle = 180.0;
static constexpr double kMinServoAngle = 0.0;
static constexpr double kDefaultMaxServoPWM = 2.4;
static constexpr double kDefaultMinServoPWM = .6;
};
} // namespace frc

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