Merge branch '2022'

This commit is contained in:
Peter Johnson
2021-05-09 14:15:40 -07:00
765 changed files with 5914 additions and 13714 deletions

View File

@@ -8,6 +8,7 @@
#include "frc/DriverStation.h"
#include "frc/Timer.h"
#include "frc/smartdashboard/SendableBuilder.h"
#include "frc/smartdashboard/SendableRegistry.h"
using namespace frc;
@@ -134,3 +135,9 @@ void ADXRS450_Gyro::Calibrate() {
int ADXRS450_Gyro::GetPort() const {
return m_port;
}
void ADXRS450_Gyro::InitSendable(SendableBuilder& builder) {
builder.SetSmartDashboardType("Gyro");
builder.AddDoubleProperty(
"Value", [=]() { return GetAngle(); }, nullptr);
}

View File

@@ -9,22 +9,25 @@
#include <hal/HALBase.h>
#include <hal/PWM.h>
#include <hal/Ports.h>
#include <wpi/StackTrace.h>
#include "frc/WPIErrors.h"
#include "frc/Errors.h"
using namespace frc;
AddressableLED::AddressableLED(int port) {
int32_t status = 0;
m_pwmHandle = HAL_InitializePWMPort(HAL_GetPort(port), &status);
wpi_setHALErrorWithRange(status, 0, HAL_GetNumPWMChannels(), port);
auto stack = wpi::GetStackTrace(1);
m_pwmHandle =
HAL_InitializePWMPort(HAL_GetPort(port), stack.c_str(), &status);
FRC_CheckErrorStatus(status, "Port " + wpi::Twine{port});
if (m_pwmHandle == HAL_kInvalidHandle) {
return;
}
m_handle = HAL_InitializeAddressableLED(m_pwmHandle, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Port " + wpi::Twine{port});
if (m_handle == HAL_kInvalidHandle) {
HAL_FreePWMPort(m_pwmHandle, &status);
}
@@ -36,12 +39,13 @@ AddressableLED::~AddressableLED() {
HAL_FreeAddressableLED(m_handle);
int32_t status = 0;
HAL_FreePWMPort(m_pwmHandle, &status);
FRC_ReportError(status, "FreePWM");
}
void AddressableLED::SetLength(int length) {
int32_t status = 0;
HAL_SetAddressableLEDLength(m_handle, length, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "length " + wpi::Twine{length});
}
static_assert(sizeof(AddressableLED::LEDData) == sizeof(HAL_AddressableLEDData),
@@ -51,14 +55,14 @@ void AddressableLED::SetData(wpi::ArrayRef<LEDData> ledData) {
int32_t status = 0;
HAL_WriteAddressableLEDData(m_handle, ledData.begin(), ledData.size(),
&status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "SetData");
}
void AddressableLED::SetData(std::initializer_list<LEDData> ledData) {
int32_t status = 0;
HAL_WriteAddressableLEDData(m_handle, ledData.begin(), ledData.size(),
&status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "SetData");
}
void AddressableLED::SetBitTiming(units::nanosecond_t lowTime0,
@@ -69,25 +73,25 @@ void AddressableLED::SetBitTiming(units::nanosecond_t lowTime0,
HAL_SetAddressableLEDBitTiming(
m_handle, lowTime0.to<int32_t>(), highTime0.to<int32_t>(),
lowTime1.to<int32_t>(), highTime1.to<int32_t>(), &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "SetBitTiming");
}
void AddressableLED::SetSyncTime(units::microsecond_t syncTime) {
int32_t status = 0;
HAL_SetAddressableLEDSyncTime(m_handle, syncTime.to<int32_t>(), &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "SetSyncTime");
}
void AddressableLED::Start() {
int32_t status = 0;
HAL_StartAddressableLEDOutput(m_handle, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Start");
}
void AddressableLED::Stop() {
int32_t status = 0;
HAL_StopAddressableLEDOutput(m_handle, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Stop");
}
void AddressableLED::LEDData::SetHSV(int h, int s, int v) {

View File

@@ -7,7 +7,7 @@
#include <hal/FRCUsageReporting.h>
#include "frc/Base.h"
#include "frc/WPIErrors.h"
#include "frc/Errors.h"
#include "frc/smartdashboard/SendableBuilder.h"
#include "frc/smartdashboard/SendableRegistry.h"
@@ -20,20 +20,18 @@ AnalogAccelerometer::AnalogAccelerometer(int channel)
AnalogAccelerometer::AnalogAccelerometer(AnalogInput* channel)
: m_analogInput(channel, NullDeleter<AnalogInput>()) {
if (channel == nullptr) {
wpi_setWPIError(NullParameter);
} else {
InitAccelerometer();
if (!channel) {
throw FRC_MakeError(err::NullParameter, "channel");
}
InitAccelerometer();
}
AnalogAccelerometer::AnalogAccelerometer(std::shared_ptr<AnalogInput> channel)
: m_analogInput(channel) {
if (channel == nullptr) {
wpi_setWPIError(NullParameter);
} else {
InitAccelerometer();
if (!channel) {
throw FRC_MakeError(err::NullParameter, "channel");
}
InitAccelerometer();
}
double AnalogAccelerometer::GetAcceleration() const {
@@ -48,10 +46,6 @@ void AnalogAccelerometer::SetZero(double zero) {
m_zeroGVoltage = zero;
}
double AnalogAccelerometer::PIDGet() {
return GetAcceleration();
}
void AnalogAccelerometer::InitSendable(SendableBuilder& builder) {
builder.SetSmartDashboardType("Accelerometer");
builder.AddDoubleProperty(

View File

@@ -10,11 +10,13 @@
#include <hal/AnalogGyro.h>
#include <hal/Errors.h>
#include <hal/FRCUsageReporting.h>
#include <wpi/StackTrace.h>
#include "frc/AnalogInput.h"
#include "frc/Base.h"
#include "frc/Errors.h"
#include "frc/Timer.h"
#include "frc/WPIErrors.h"
#include "frc/smartdashboard/SendableBuilder.h"
#include "frc/smartdashboard/SendableRegistry.h"
using namespace frc;
@@ -30,12 +32,11 @@ AnalogGyro::AnalogGyro(AnalogInput* channel)
AnalogGyro::AnalogGyro(std::shared_ptr<AnalogInput> channel)
: m_analog(channel) {
if (channel == nullptr) {
wpi_setWPIError(NullParameter);
} else {
InitGyro();
Calibrate();
if (!channel) {
throw FRC_MakeError(err::NullParameter, "channel");
}
InitGyro();
Calibrate();
}
AnalogGyro::AnalogGyro(int channel, int center, double offset)
@@ -46,20 +47,15 @@ AnalogGyro::AnalogGyro(int channel, int center, double offset)
AnalogGyro::AnalogGyro(std::shared_ptr<AnalogInput> channel, int center,
double offset)
: m_analog(channel) {
if (channel == nullptr) {
wpi_setWPIError(NullParameter);
} else {
InitGyro();
int32_t status = 0;
HAL_SetAnalogGyroParameters(m_gyroHandle, kDefaultVoltsPerDegreePerSecond,
offset, center, &status);
if (status != 0) {
wpi_setHALError(status);
m_gyroHandle = HAL_kInvalidHandle;
return;
}
Reset();
if (!channel) {
throw FRC_MakeError(err::NullParameter, "channel");
}
InitGyro();
int32_t status = 0;
HAL_SetAnalogGyroParameters(m_gyroHandle, kDefaultVoltsPerDegreePerSecond,
offset, center, &status);
FRC_CheckErrorStatus(status, "SetAnalogGyroParameters");
Reset();
}
AnalogGyro::~AnalogGyro() {
@@ -67,42 +63,30 @@ AnalogGyro::~AnalogGyro() {
}
double AnalogGyro::GetAngle() const {
if (StatusIsFatal()) {
return 0.0;
}
int32_t status = 0;
double value = HAL_GetAnalogGyroAngle(m_gyroHandle, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "GetAngle");
return value;
}
double AnalogGyro::GetRate() const {
if (StatusIsFatal()) {
return 0.0;
}
int32_t status = 0;
double value = HAL_GetAnalogGyroRate(m_gyroHandle, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "GetRate");
return value;
}
int AnalogGyro::GetCenter() const {
if (StatusIsFatal()) {
return 0;
}
int32_t status = 0;
int value = HAL_GetAnalogGyroCenter(m_gyroHandle, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "GetCenter");
return value;
}
double AnalogGyro::GetOffset() const {
if (StatusIsFatal()) {
return 0.0;
}
int32_t status = 0;
double value = HAL_GetAnalogGyroOffset(m_gyroHandle, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "GetOffset");
return value;
}
@@ -110,57 +94,33 @@ void AnalogGyro::SetSensitivity(double voltsPerDegreePerSecond) {
int32_t status = 0;
HAL_SetAnalogGyroVoltsPerDegreePerSecond(m_gyroHandle,
voltsPerDegreePerSecond, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "SetSensitivity");
}
void AnalogGyro::SetDeadband(double volts) {
if (StatusIsFatal()) {
return;
}
int32_t status = 0;
HAL_SetAnalogGyroDeadband(m_gyroHandle, volts, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "SetDeadband");
}
void AnalogGyro::Reset() {
if (StatusIsFatal()) {
return;
}
int32_t status = 0;
HAL_ResetAnalogGyro(m_gyroHandle, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Reset");
}
void AnalogGyro::InitGyro() {
if (StatusIsFatal()) {
return;
}
if (m_gyroHandle == HAL_kInvalidHandle) {
int32_t status = 0;
m_gyroHandle = HAL_InitializeAnalogGyro(m_analog->m_port, &status);
if (status == PARAMETER_OUT_OF_RANGE) {
wpi_setWPIErrorWithContext(ParameterOutOfRange,
" channel (must be accumulator channel)");
m_analog = nullptr;
m_gyroHandle = HAL_kInvalidHandle;
return;
}
if (status != 0) {
wpi_setHALError(status);
m_analog = nullptr;
m_gyroHandle = HAL_kInvalidHandle;
return;
}
std::string stackTrace = wpi::GetStackTrace(1);
m_gyroHandle =
HAL_InitializeAnalogGyro(m_analog->m_port, stackTrace.c_str(), &status);
FRC_CheckErrorStatus(status, "InitializeAnalogGyro");
}
int32_t status = 0;
HAL_SetupAnalogGyro(m_gyroHandle, &status);
if (status != 0) {
wpi_setHALError(status);
m_analog = nullptr;
m_gyroHandle = HAL_kInvalidHandle;
return;
}
FRC_CheckErrorStatus(status, "SetupAnalogGyro");
HAL_Report(HALUsageReporting::kResourceType_Gyro, m_analog->GetChannel() + 1);
@@ -169,14 +129,17 @@ void AnalogGyro::InitGyro() {
}
void AnalogGyro::Calibrate() {
if (StatusIsFatal()) {
return;
}
int32_t status = 0;
HAL_CalibrateAnalogGyro(m_gyroHandle, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Calibrate");
}
std::shared_ptr<AnalogInput> AnalogGyro::GetAnalogInput() const {
return m_analog;
}
void AnalogGyro::InitSendable(SendableBuilder& builder) {
builder.SetSmartDashboardType("Gyro");
builder.AddDoubleProperty(
"Value", [=]() { return GetAngle(); }, nullptr);
}

View File

@@ -9,10 +9,11 @@
#include <hal/FRCUsageReporting.h>
#include <hal/HALBase.h>
#include <hal/Ports.h>
#include <wpi/StackTrace.h>
#include "frc/Errors.h"
#include "frc/SensorUtil.h"
#include "frc/Timer.h"
#include "frc/WPIErrors.h"
#include "frc/smartdashboard/SendableBuilder.h"
#include "frc/smartdashboard/SendableRegistry.h"
@@ -20,22 +21,17 @@ using namespace frc;
AnalogInput::AnalogInput(int channel) {
if (!SensorUtil::CheckAnalogInputChannel(channel)) {
wpi_setWPIErrorWithContext(ChannelIndexOutOfRange,
"Analog Input " + wpi::Twine(channel));
return;
throw FRC_MakeError(err::ChannelIndexOutOfRange,
"Analog Input " + wpi::Twine{channel});
}
m_channel = channel;
HAL_PortHandle port = HAL_GetPort(channel);
int32_t status = 0;
m_port = HAL_InitializeAnalogInputPort(port, &status);
if (status != 0) {
wpi_setHALErrorWithRange(status, 0, HAL_GetNumAnalogInputs(), channel);
m_channel = std::numeric_limits<int>::max();
m_port = HAL_kInvalidHandle;
return;
}
std::string stackTrace = wpi::GetStackTrace(1);
m_port = HAL_InitializeAnalogInputPort(port, stackTrace.c_str(), &status);
FRC_CheckErrorStatus(status, "Analog Input " + wpi::Twine{channel});
HAL_Report(HALUsageReporting::kResourceType_AnalogChannel, channel + 1);
@@ -47,220 +43,154 @@ AnalogInput::~AnalogInput() {
}
int AnalogInput::GetValue() const {
if (StatusIsFatal()) {
return 0;
}
int32_t status = 0;
int value = HAL_GetAnalogValue(m_port, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Analog Input " + wpi::Twine{m_channel});
return value;
}
int AnalogInput::GetAverageValue() const {
if (StatusIsFatal()) {
return 0;
}
int32_t status = 0;
int value = HAL_GetAnalogAverageValue(m_port, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Analog Input " + wpi::Twine{m_channel});
return value;
}
double AnalogInput::GetVoltage() const {
if (StatusIsFatal()) {
return 0.0;
}
int32_t status = 0;
double voltage = HAL_GetAnalogVoltage(m_port, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Analog Input " + wpi::Twine{m_channel});
return voltage;
}
double AnalogInput::GetAverageVoltage() const {
if (StatusIsFatal()) {
return 0.0;
}
int32_t status = 0;
double voltage = HAL_GetAnalogAverageVoltage(m_port, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Analog Input " + wpi::Twine{m_channel});
return voltage;
}
int AnalogInput::GetChannel() const {
if (StatusIsFatal()) {
return 0;
}
return m_channel;
}
void AnalogInput::SetAverageBits(int bits) {
if (StatusIsFatal()) {
return;
}
int32_t status = 0;
HAL_SetAnalogAverageBits(m_port, bits, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Analog Input " + wpi::Twine{m_channel});
}
int AnalogInput::GetAverageBits() const {
int32_t status = 0;
int averageBits = HAL_GetAnalogAverageBits(m_port, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Analog Input " + wpi::Twine{m_channel});
return averageBits;
}
void AnalogInput::SetOversampleBits(int bits) {
if (StatusIsFatal()) {
return;
}
int32_t status = 0;
HAL_SetAnalogOversampleBits(m_port, bits, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Analog Input " + wpi::Twine{m_channel});
}
int AnalogInput::GetOversampleBits() const {
if (StatusIsFatal()) {
return 0;
}
int32_t status = 0;
int oversampleBits = HAL_GetAnalogOversampleBits(m_port, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Analog Input " + wpi::Twine{m_channel});
return oversampleBits;
}
int AnalogInput::GetLSBWeight() const {
if (StatusIsFatal()) {
return 0;
}
int32_t status = 0;
int lsbWeight = HAL_GetAnalogLSBWeight(m_port, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Analog Input " + wpi::Twine{m_channel});
return lsbWeight;
}
int AnalogInput::GetOffset() const {
if (StatusIsFatal()) {
return 0;
}
int32_t status = 0;
int offset = HAL_GetAnalogOffset(m_port, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Analog Input " + wpi::Twine{m_channel});
return offset;
}
bool AnalogInput::IsAccumulatorChannel() const {
if (StatusIsFatal()) {
return false;
}
int32_t status = 0;
bool isAccum = HAL_IsAccumulatorChannel(m_port, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Analog Input " + wpi::Twine{m_channel});
return isAccum;
}
void AnalogInput::InitAccumulator() {
if (StatusIsFatal()) {
return;
}
m_accumulatorOffset = 0;
int32_t status = 0;
HAL_InitAccumulator(m_port, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Analog Input " + wpi::Twine{m_channel});
}
void AnalogInput::SetAccumulatorInitialValue(int64_t initialValue) {
if (StatusIsFatal()) {
return;
}
m_accumulatorOffset = initialValue;
}
void AnalogInput::ResetAccumulator() {
if (StatusIsFatal()) {
return;
}
int32_t status = 0;
HAL_ResetAccumulator(m_port, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Analog Input " + wpi::Twine{m_channel});
if (!StatusIsFatal()) {
// Wait until the next sample, so the next call to GetAccumulator*()
// won't have old values.
const double sampleTime = 1.0 / GetSampleRate();
const double overSamples = 1 << GetOversampleBits();
const double averageSamples = 1 << GetAverageBits();
Wait(sampleTime * overSamples * averageSamples);
}
// Wait until the next sample, so the next call to GetAccumulator*()
// won't have old values.
const double sampleTime = 1.0 / GetSampleRate();
const double overSamples = 1 << GetOversampleBits();
const double averageSamples = 1 << GetAverageBits();
Wait(sampleTime * overSamples * averageSamples);
}
void AnalogInput::SetAccumulatorCenter(int center) {
if (StatusIsFatal()) {
return;
}
int32_t status = 0;
HAL_SetAccumulatorCenter(m_port, center, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Analog Input " + wpi::Twine{m_channel});
}
void AnalogInput::SetAccumulatorDeadband(int deadband) {
if (StatusIsFatal()) {
return;
}
int32_t status = 0;
HAL_SetAccumulatorDeadband(m_port, deadband, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Analog Input " + wpi::Twine{m_channel});
}
int64_t AnalogInput::GetAccumulatorValue() const {
if (StatusIsFatal()) {
return 0;
}
int32_t status = 0;
int64_t value = HAL_GetAccumulatorValue(m_port, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Analog Input " + wpi::Twine{m_channel});
return value + m_accumulatorOffset;
}
int64_t AnalogInput::GetAccumulatorCount() const {
if (StatusIsFatal()) {
return 0;
}
int32_t status = 0;
int64_t count = HAL_GetAccumulatorCount(m_port, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Analog Input " + wpi::Twine{m_channel});
return count;
}
void AnalogInput::GetAccumulatorOutput(int64_t& value, int64_t& count) const {
if (StatusIsFatal()) {
return;
}
int32_t status = 0;
HAL_GetAccumulatorOutput(m_port, &value, &count, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Analog Input " + wpi::Twine{m_channel});
value += m_accumulatorOffset;
}
void AnalogInput::SetSampleRate(double samplesPerSecond) {
int32_t status = 0;
HAL_SetAnalogSampleRate(samplesPerSecond, &status);
wpi_setGlobalHALError(status);
FRC_CheckErrorStatus(status, "SetSampleRate");
}
double AnalogInput::GetSampleRate() {
int32_t status = 0;
double sampleRate = HAL_GetAnalogSampleRate(&status);
wpi_setGlobalHALError(status);
FRC_CheckErrorStatus(status, "GetSampleRate");
return sampleRate;
}
double AnalogInput::PIDGet() {
if (StatusIsFatal()) {
return 0.0;
}
return GetAverageVoltage();
}
void AnalogInput::SetSimDevice(HAL_SimDeviceHandle device) {
HAL_SetAnalogInputSimDevice(m_port, device);
}

View File

@@ -11,9 +11,10 @@
#include <hal/FRCUsageReporting.h>
#include <hal/HALBase.h>
#include <hal/Ports.h>
#include <wpi/StackTrace.h>
#include "frc/Errors.h"
#include "frc/SensorUtil.h"
#include "frc/WPIErrors.h"
#include "frc/smartdashboard/SendableBuilder.h"
#include "frc/smartdashboard/SendableRegistry.h"
@@ -21,24 +22,17 @@ using namespace frc;
AnalogOutput::AnalogOutput(int channel) {
if (!SensorUtil::CheckAnalogOutputChannel(channel)) {
wpi_setWPIErrorWithContext(ChannelIndexOutOfRange,
"analog output " + wpi::Twine(channel));
m_channel = std::numeric_limits<int>::max();
m_port = HAL_kInvalidHandle;
return;
throw FRC_MakeError(err::ChannelIndexOutOfRange,
"analog output " + wpi::Twine(channel));
}
m_channel = channel;
HAL_PortHandle port = HAL_GetPort(m_channel);
int32_t status = 0;
m_port = HAL_InitializeAnalogOutputPort(port, &status);
if (status != 0) {
wpi_setHALErrorWithRange(status, 0, HAL_GetNumAnalogOutputs(), channel);
m_channel = std::numeric_limits<int>::max();
m_port = HAL_kInvalidHandle;
return;
}
std::string stackTrace = wpi::GetStackTrace(1);
m_port = HAL_InitializeAnalogOutputPort(port, stackTrace.c_str(), &status);
FRC_CheckErrorStatus(status, "analog output " + wpi::Twine(channel));
HAL_Report(HALUsageReporting::kResourceType_AnalogOutput, m_channel + 1);
SendableRegistry::GetInstance().AddLW(this, "AnalogOutput", m_channel);
@@ -51,16 +45,13 @@ AnalogOutput::~AnalogOutput() {
void AnalogOutput::SetVoltage(double voltage) {
int32_t status = 0;
HAL_SetAnalogOutput(m_port, voltage, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "SetVoltage");
}
double AnalogOutput::GetVoltage() const {
int32_t status = 0;
double voltage = HAL_GetAnalogOutput(m_port, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "GetVoltage");
return voltage;
}

View File

@@ -42,10 +42,6 @@ double AnalogPotentiometer::Get() const {
m_offset;
}
double AnalogPotentiometer::PIDGet() {
return Get();
}
void AnalogPotentiometer::InitSendable(SendableBuilder& builder) {
builder.SetSmartDashboardType("Analog Input");
builder.AddDoubleProperty(

View File

@@ -11,7 +11,7 @@
#include "frc/AnalogInput.h"
#include "frc/Base.h"
#include "frc/DutyCycle.h"
#include "frc/WPIErrors.h"
#include "frc/Errors.h"
#include "frc/smartdashboard/SendableRegistry.h"
using namespace frc;
@@ -26,11 +26,7 @@ AnalogTrigger::AnalogTrigger(AnalogInput* input) {
m_analogInput = input;
int32_t status = 0;
m_trigger = HAL_InitializeAnalogTrigger(input->m_port, &status);
if (status != 0) {
wpi_setHALError(status);
m_trigger = HAL_kInvalidHandle;
return;
}
FRC_CheckErrorStatus(status, "InitializeAnalogTrigger");
int index = GetIndex();
HAL_Report(HALUsageReporting::kResourceType_AnalogTrigger, index + 1);
@@ -41,11 +37,7 @@ AnalogTrigger::AnalogTrigger(DutyCycle* input) {
m_dutyCycle = input;
int32_t status = 0;
m_trigger = HAL_InitializeAnalogTriggerDutyCycle(input->m_handle, &status);
if (status != 0) {
wpi_setHALError(status);
m_trigger = HAL_kInvalidHandle;
return;
}
FRC_CheckErrorStatus(status, "InitializeAnalogTriggerDutyCycle");
int index = GetIndex();
HAL_Report(HALUsageReporting::kResourceType_AnalogTrigger, index + 1);
@@ -55,6 +47,7 @@ AnalogTrigger::AnalogTrigger(DutyCycle* input) {
AnalogTrigger::~AnalogTrigger() {
int32_t status = 0;
HAL_CleanAnalogTrigger(m_trigger, &status);
FRC_ReportError(status, "CleanAnalogTrigger");
if (m_ownsAnalog) {
delete m_analogInput;
@@ -62,16 +55,13 @@ AnalogTrigger::~AnalogTrigger() {
}
AnalogTrigger::AnalogTrigger(AnalogTrigger&& rhs)
: ErrorBase(std::move(rhs)),
SendableHelper(std::move(rhs)),
m_trigger(std::move(rhs.m_trigger)) {
: SendableHelper(std::move(rhs)), m_trigger(std::move(rhs.m_trigger)) {
std::swap(m_analogInput, rhs.m_analogInput);
std::swap(m_dutyCycle, rhs.m_dutyCycle);
std::swap(m_ownsAnalog, rhs.m_ownsAnalog);
}
AnalogTrigger& AnalogTrigger::operator=(AnalogTrigger&& rhs) {
ErrorBase::operator=(std::move(rhs));
SendableHelper::operator=(std::move(rhs));
m_trigger = std::move(rhs.m_trigger);
@@ -83,85 +73,58 @@ AnalogTrigger& AnalogTrigger::operator=(AnalogTrigger&& rhs) {
}
void AnalogTrigger::SetLimitsVoltage(double lower, double upper) {
if (StatusIsFatal()) {
return;
}
int32_t status = 0;
HAL_SetAnalogTriggerLimitsVoltage(m_trigger, lower, upper, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "SetLimitsVoltage");
}
void AnalogTrigger::SetLimitsDutyCycle(double lower, double upper) {
if (StatusIsFatal()) {
return;
}
int32_t status = 0;
HAL_SetAnalogTriggerLimitsDutyCycle(m_trigger, lower, upper, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "SetLimitsDutyCycle");
}
void AnalogTrigger::SetLimitsRaw(int lower, int upper) {
if (StatusIsFatal()) {
return;
}
int32_t status = 0;
HAL_SetAnalogTriggerLimitsRaw(m_trigger, lower, upper, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "SetLimitsRaw");
}
void AnalogTrigger::SetAveraged(bool useAveragedValue) {
if (StatusIsFatal()) {
return;
}
int32_t status = 0;
HAL_SetAnalogTriggerAveraged(m_trigger, useAveragedValue, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "SetAveraged");
}
void AnalogTrigger::SetFiltered(bool useFilteredValue) {
if (StatusIsFatal()) {
return;
}
int32_t status = 0;
HAL_SetAnalogTriggerFiltered(m_trigger, useFilteredValue, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "SetFiltered");
}
int AnalogTrigger::GetIndex() const {
if (StatusIsFatal()) {
return -1;
}
int32_t status = 0;
auto ret = HAL_GetAnalogTriggerFPGAIndex(m_trigger, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "GetIndex");
return ret;
}
bool AnalogTrigger::GetInWindow() {
if (StatusIsFatal()) {
return false;
}
int32_t status = 0;
bool result = HAL_GetAnalogTriggerInWindow(m_trigger, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "GetInWindow");
return result;
}
bool AnalogTrigger::GetTriggerState() {
if (StatusIsFatal()) {
return false;
}
int32_t status = 0;
bool result = HAL_GetAnalogTriggerTriggerState(m_trigger, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "GetTriggerState");
return result;
}
std::shared_ptr<AnalogTriggerOutput> AnalogTrigger::CreateOutput(
AnalogTriggerType type) const {
if (StatusIsFatal()) {
return nullptr;
}
return std::shared_ptr<AnalogTriggerOutput>(
new AnalogTriggerOutput(*this, type), NullDeleter<AnalogTriggerOutput>());
}

View File

@@ -7,7 +7,7 @@
#include <hal/FRCUsageReporting.h>
#include "frc/AnalogTrigger.h"
#include "frc/WPIErrors.h"
#include "frc/Errors.h"
using namespace frc;
@@ -16,7 +16,7 @@ bool AnalogTriggerOutput::Get() const {
bool result = HAL_GetAnalogTriggerOutput(
m_trigger->m_trigger, static_cast<HAL_AnalogTriggerType>(m_outputType),
&status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Get");
return result;
}

View File

@@ -7,7 +7,7 @@
#include <hal/Accelerometer.h>
#include <hal/FRCUsageReporting.h>
#include "frc/WPIErrors.h"
#include "frc/Errors.h"
#include "frc/smartdashboard/SendableBuilder.h"
#include "frc/smartdashboard/SendableRegistry.h"
@@ -23,8 +23,8 @@ BuiltInAccelerometer::BuiltInAccelerometer(Range range) {
void BuiltInAccelerometer::SetRange(Range range) {
if (range == kRange_16G) {
wpi_setWPIErrorWithContext(
ParameterOutOfRange, "16G range not supported (use k2G, k4G, or k8G)");
throw FRC_MakeError(err::ParameterOutOfRange,
"16G range not supported (use k2G, k4G, or k8G)");
}
HAL_SetAccelerometerActive(false);

View File

@@ -11,17 +11,15 @@
#include <hal/Errors.h>
#include <hal/FRCUsageReporting.h>
#include "frc/Errors.h"
using namespace frc;
CAN::CAN(int deviceId) {
int32_t status = 0;
m_handle =
HAL_InitializeCAN(kTeamManufacturer, deviceId, kTeamDeviceType, &status);
if (status != 0) {
wpi_setHALError(status);
m_handle = HAL_kInvalidHandle;
return;
}
FRC_CheckErrorStatus(status, "device id " + wpi::Twine{deviceId});
HAL_Report(HALUsageReporting::kResourceType_CAN, deviceId + 1);
}
@@ -31,19 +29,14 @@ CAN::CAN(int deviceId, int deviceManufacturer, int deviceType) {
m_handle = HAL_InitializeCAN(
static_cast<HAL_CANManufacturer>(deviceManufacturer), deviceId,
static_cast<HAL_CANDeviceType>(deviceType), &status);
if (status != 0) {
wpi_setHALError(status);
m_handle = HAL_kInvalidHandle;
return;
}
FRC_CheckErrorStatus(status, "device id " + wpi::Twine{deviceId} + " mfg " +
wpi::Twine{deviceManufacturer} + " type " +
wpi::Twine{deviceType});
HAL_Report(HALUsageReporting::kResourceType_CAN, deviceId + 1);
}
CAN::~CAN() {
if (StatusIsFatal()) {
return;
}
if (m_handle != HAL_kInvalidHandle) {
HAL_CleanCAN(m_handle);
m_handle = HAL_kInvalidHandle;
@@ -53,20 +46,20 @@ CAN::~CAN() {
void CAN::WritePacket(const uint8_t* data, int length, int apiId) {
int32_t status = 0;
HAL_WriteCANPacket(m_handle, data, length, apiId, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "WritePacket");
}
void CAN::WritePacketRepeating(const uint8_t* data, int length, int apiId,
int repeatMs) {
int32_t status = 0;
HAL_WriteCANPacketRepeating(m_handle, data, length, apiId, repeatMs, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "WritePacketRepeating");
}
void CAN::WriteRTRFrame(int length, int apiId) {
int32_t status = 0;
HAL_WriteCANRTRFrame(m_handle, length, apiId, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "WriteRTRFrame");
}
int CAN::WritePacketNoError(const uint8_t* data, int length, int apiId) {
@@ -91,7 +84,7 @@ int CAN::WriteRTRFrameNoError(int length, int apiId) {
void CAN::StopPacketRepeating(int apiId) {
int32_t status = 0;
HAL_StopCANPacketRepeating(m_handle, apiId, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "StopPacketRepeating");
}
bool CAN::ReadPacketNew(int apiId, CANData* data) {
@@ -102,7 +95,7 @@ bool CAN::ReadPacketNew(int apiId, CANData* data) {
return false;
}
if (status != 0) {
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "ReadPacketNew");
return false;
} else {
return true;
@@ -117,7 +110,7 @@ bool CAN::ReadPacketLatest(int apiId, CANData* data) {
return false;
}
if (status != 0) {
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "ReadPacketLatest");
return false;
} else {
return true;
@@ -133,7 +126,7 @@ bool CAN::ReadPacketTimeout(int apiId, int timeoutMs, CANData* data) {
return false;
}
if (status != 0) {
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "ReadPacketTimeout");
return false;
} else {
return true;

View File

@@ -9,7 +9,7 @@
#include <hal/Ports.h>
#include <hal/Solenoid.h>
#include "frc/WPIErrors.h"
#include "frc/Errors.h"
#include "frc/smartdashboard/SendableBuilder.h"
#include "frc/smartdashboard/SendableRegistry.h"
@@ -18,10 +18,7 @@ using namespace frc;
Compressor::Compressor(int pcmID) : m_module(pcmID) {
int32_t status = 0;
m_compressorHandle = HAL_InitializeCompressor(m_module, &status);
if (status != 0) {
wpi_setHALErrorWithRange(status, 0, HAL_GetNumPCMModules(), pcmID);
return;
}
FRC_CheckErrorStatus(status, "Module " + wpi::Twine{m_module});
SetClosedLoopControl(true);
HAL_Report(HALUsageReporting::kResourceType_Compressor, pcmID + 1);
@@ -29,204 +26,96 @@ Compressor::Compressor(int pcmID) : m_module(pcmID) {
}
void Compressor::Start() {
if (StatusIsFatal()) {
return;
}
SetClosedLoopControl(true);
}
void Compressor::Stop() {
if (StatusIsFatal()) {
return;
}
SetClosedLoopControl(false);
}
bool Compressor::Enabled() const {
if (StatusIsFatal()) {
return false;
}
int32_t status = 0;
bool value;
value = HAL_GetCompressor(m_compressorHandle, &status);
if (status) {
wpi_setWPIError(Timeout);
}
bool value = HAL_GetCompressor(m_compressorHandle, &status);
FRC_CheckErrorStatus(status, "Module " + wpi::Twine{m_module});
return value;
}
bool Compressor::GetPressureSwitchValue() const {
if (StatusIsFatal()) {
return false;
}
int32_t status = 0;
bool value;
value = HAL_GetCompressorPressureSwitch(m_compressorHandle, &status);
if (status) {
wpi_setWPIError(Timeout);
}
bool value = HAL_GetCompressorPressureSwitch(m_compressorHandle, &status);
FRC_CheckErrorStatus(status, "Module " + wpi::Twine{m_module});
return value;
}
double Compressor::GetCompressorCurrent() const {
if (StatusIsFatal()) {
return 0;
}
int32_t status = 0;
double value;
value = HAL_GetCompressorCurrent(m_compressorHandle, &status);
if (status) {
wpi_setWPIError(Timeout);
}
double value = HAL_GetCompressorCurrent(m_compressorHandle, &status);
FRC_CheckErrorStatus(status, "Module " + wpi::Twine{m_module});
return value;
}
void Compressor::SetClosedLoopControl(bool on) {
if (StatusIsFatal()) {
return;
}
int32_t status = 0;
HAL_SetCompressorClosedLoopControl(m_compressorHandle, on, &status);
if (status) {
wpi_setWPIError(Timeout);
}
FRC_CheckErrorStatus(status, "Module " + wpi::Twine{m_module});
}
bool Compressor::GetClosedLoopControl() const {
if (StatusIsFatal()) {
return false;
}
int32_t status = 0;
bool value;
value = HAL_GetCompressorClosedLoopControl(m_compressorHandle, &status);
if (status) {
wpi_setWPIError(Timeout);
}
bool value = HAL_GetCompressorClosedLoopControl(m_compressorHandle, &status);
FRC_CheckErrorStatus(status, "Module " + wpi::Twine{m_module});
return value;
}
bool Compressor::GetCompressorCurrentTooHighFault() const {
if (StatusIsFatal()) {
return false;
}
int32_t status = 0;
bool value;
value = HAL_GetCompressorCurrentTooHighFault(m_compressorHandle, &status);
if (status) {
wpi_setWPIError(Timeout);
}
bool value =
HAL_GetCompressorCurrentTooHighFault(m_compressorHandle, &status);
FRC_CheckErrorStatus(status, "Module " + wpi::Twine{m_module});
return value;
}
bool Compressor::GetCompressorCurrentTooHighStickyFault() const {
if (StatusIsFatal()) {
return false;
}
int32_t status = 0;
bool value;
value =
bool value =
HAL_GetCompressorCurrentTooHighStickyFault(m_compressorHandle, &status);
if (status) {
wpi_setWPIError(Timeout);
}
FRC_CheckErrorStatus(status, "Module " + wpi::Twine{m_module});
return value;
}
bool Compressor::GetCompressorShortedStickyFault() const {
if (StatusIsFatal()) {
return false;
}
int32_t status = 0;
bool value;
value = HAL_GetCompressorShortedStickyFault(m_compressorHandle, &status);
if (status) {
wpi_setWPIError(Timeout);
}
bool value = HAL_GetCompressorShortedStickyFault(m_compressorHandle, &status);
FRC_CheckErrorStatus(status, "Module " + wpi::Twine{m_module});
return value;
}
bool Compressor::GetCompressorShortedFault() const {
if (StatusIsFatal()) {
return false;
}
int32_t status = 0;
bool value;
value = HAL_GetCompressorShortedFault(m_compressorHandle, &status);
if (status) {
wpi_setWPIError(Timeout);
}
bool value = HAL_GetCompressorShortedFault(m_compressorHandle, &status);
FRC_CheckErrorStatus(status, "Module " + wpi::Twine{m_module});
return value;
}
bool Compressor::GetCompressorNotConnectedStickyFault() const {
if (StatusIsFatal()) {
return false;
}
int32_t status = 0;
bool value;
value = HAL_GetCompressorNotConnectedStickyFault(m_compressorHandle, &status);
if (status) {
wpi_setWPIError(Timeout);
}
bool value =
HAL_GetCompressorNotConnectedStickyFault(m_compressorHandle, &status);
FRC_CheckErrorStatus(status, "Module " + wpi::Twine{m_module});
return value;
}
bool Compressor::GetCompressorNotConnectedFault() const {
if (StatusIsFatal()) {
return false;
}
int32_t status = 0;
bool value;
value = HAL_GetCompressorNotConnectedFault(m_compressorHandle, &status);
if (status) {
wpi_setWPIError(Timeout);
}
bool value = HAL_GetCompressorNotConnectedFault(m_compressorHandle, &status);
FRC_CheckErrorStatus(status, "Module " + wpi::Twine{m_module});
return value;
}
void Compressor::ClearAllPCMStickyFaults() {
if (StatusIsFatal()) {
return;
}
int32_t status = 0;
HAL_ClearAllPCMStickyFaults(m_module, &status);
if (status) {
wpi_setWPIError(Timeout);
}
FRC_CheckErrorStatus(status, "Module " + wpi::Twine{m_module});
}
int Compressor::GetModule() const {

View File

@@ -12,7 +12,7 @@
#include "frc/AnalogTrigger.h"
#include "frc/Base.h"
#include "frc/DigitalInput.h"
#include "frc/WPIErrors.h"
#include "frc/Errors.h"
#include "frc/smartdashboard/SendableBuilder.h"
#include "frc/smartdashboard/SendableRegistry.h"
@@ -22,7 +22,7 @@ Counter::Counter(Mode mode) {
int32_t status = 0;
m_counter = HAL_InitializeCounter(static_cast<HAL_Counter_Mode>(mode),
&m_index, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "InitializeCounter");
SetMaxPeriod(0.5);
@@ -64,10 +64,8 @@ Counter::Counter(EncodingType encodingType,
std::shared_ptr<DigitalSource> downSource, bool inverted)
: Counter(kExternalDirection) {
if (encodingType != k1X && encodingType != k2X) {
wpi_setWPIErrorWithContext(
ParameterOutOfRange,
"Counter only supports 1X and 2X quadrature decoding.");
return;
throw FRC_MakeError(err::ParameterOutOfRange,
"Counter only supports 1X and 2X quadrature decoding.");
}
SetUpSource(upSource);
SetDownSource(downSource);
@@ -81,22 +79,23 @@ Counter::Counter(EncodingType encodingType,
HAL_SetCounterAverageSize(m_counter, 2, &status);
}
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Counter constructor");
SetDownSourceEdge(inverted, true);
}
Counter::~Counter() {
SetUpdateWhenEmpty(true);
try {
SetUpdateWhenEmpty(true);
} catch (const RuntimeError& e) {
e.Report();
}
int32_t status = 0;
HAL_FreeCounter(m_counter, &status);
wpi_setHALError(status);
FRC_ReportError(status, "Counter destructor");
}
void Counter::SetUpSource(int channel) {
if (StatusIsFatal()) {
return;
}
SetUpSource(std::make_shared<DigitalInput>(channel));
SendableRegistry::GetInstance().AddChild(this, m_upSource.get());
}
@@ -110,9 +109,6 @@ void Counter::SetUpSource(AnalogTrigger* analogTrigger,
void Counter::SetUpSource(std::shared_ptr<AnalogTrigger> analogTrigger,
AnalogTriggerType triggerType) {
if (StatusIsFatal()) {
return;
}
SetUpSource(analogTrigger->CreateOutput(triggerType));
}
@@ -122,20 +118,13 @@ void Counter::SetUpSource(DigitalSource* source) {
}
void Counter::SetUpSource(std::shared_ptr<DigitalSource> source) {
if (StatusIsFatal()) {
return;
}
m_upSource = source;
if (m_upSource->StatusIsFatal()) {
CloneError(*m_upSource);
} else {
int32_t status = 0;
HAL_SetCounterUpSource(m_counter, source->GetPortHandleForRouting(),
static_cast<HAL_AnalogTriggerType>(
source->GetAnalogTriggerTypeForRouting()),
&status);
wpi_setHALError(status);
}
int32_t status = 0;
HAL_SetCounterUpSource(m_counter, source->GetPortHandleForRouting(),
static_cast<HAL_AnalogTriggerType>(
source->GetAnalogTriggerTypeForRouting()),
&status);
FRC_CheckErrorStatus(status, "SetUpSource");
}
void Counter::SetUpSource(DigitalSource& source) {
@@ -144,33 +133,24 @@ void Counter::SetUpSource(DigitalSource& source) {
}
void Counter::SetUpSourceEdge(bool risingEdge, bool fallingEdge) {
if (StatusIsFatal()) {
return;
}
if (m_upSource == nullptr) {
wpi_setWPIErrorWithContext(
NullParameter,
throw FRC_MakeError(
err::NullParameter,
"Must set non-nullptr UpSource before setting UpSourceEdge");
}
int32_t status = 0;
HAL_SetCounterUpSourceEdge(m_counter, risingEdge, fallingEdge, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "SetUpSourceEdge");
}
void Counter::ClearUpSource() {
if (StatusIsFatal()) {
return;
}
m_upSource.reset();
int32_t status = 0;
HAL_ClearCounterUpSource(m_counter, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "ClearUpSource");
}
void Counter::SetDownSource(int channel) {
if (StatusIsFatal()) {
return;
}
SetDownSource(std::make_shared<DigitalInput>(channel));
SendableRegistry::GetInstance().AddChild(this, m_downSource.get());
}
@@ -184,9 +164,6 @@ void Counter::SetDownSource(AnalogTrigger* analogTrigger,
void Counter::SetDownSource(std::shared_ptr<AnalogTrigger> analogTrigger,
AnalogTriggerType triggerType) {
if (StatusIsFatal()) {
return;
}
SetDownSource(analogTrigger->CreateOutput(triggerType));
}
@@ -201,106 +178,82 @@ void Counter::SetDownSource(DigitalSource& source) {
}
void Counter::SetDownSource(std::shared_ptr<DigitalSource> source) {
if (StatusIsFatal()) {
return;
}
m_downSource = source;
if (m_downSource->StatusIsFatal()) {
CloneError(*m_downSource);
} else {
int32_t status = 0;
HAL_SetCounterDownSource(m_counter, source->GetPortHandleForRouting(),
static_cast<HAL_AnalogTriggerType>(
source->GetAnalogTriggerTypeForRouting()),
&status);
wpi_setHALError(status);
}
int32_t status = 0;
HAL_SetCounterDownSource(m_counter, source->GetPortHandleForRouting(),
static_cast<HAL_AnalogTriggerType>(
source->GetAnalogTriggerTypeForRouting()),
&status);
FRC_CheckErrorStatus(status, "SetDownSource");
}
void Counter::SetDownSourceEdge(bool risingEdge, bool fallingEdge) {
if (StatusIsFatal()) {
return;
}
if (m_downSource == nullptr) {
wpi_setWPIErrorWithContext(
NullParameter,
throw FRC_MakeError(
err::NullParameter,
"Must set non-nullptr DownSource before setting DownSourceEdge");
}
int32_t status = 0;
HAL_SetCounterDownSourceEdge(m_counter, risingEdge, fallingEdge, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "SetDownSourceEdge");
}
void Counter::ClearDownSource() {
if (StatusIsFatal()) {
return;
}
m_downSource.reset();
int32_t status = 0;
HAL_ClearCounterDownSource(m_counter, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "ClearDownSource");
}
void Counter::SetUpDownCounterMode() {
if (StatusIsFatal()) {
return;
}
int32_t status = 0;
HAL_SetCounterUpDownMode(m_counter, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "SetUpDownCounterMode");
}
void Counter::SetExternalDirectionMode() {
if (StatusIsFatal()) {
return;
}
int32_t status = 0;
HAL_SetCounterExternalDirectionMode(m_counter, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "SetExternalDirectionMode");
}
void Counter::SetSemiPeriodMode(bool highSemiPeriod) {
if (StatusIsFatal()) {
return;
}
int32_t status = 0;
HAL_SetCounterSemiPeriodMode(m_counter, highSemiPeriod, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(
status,
"SetSemiPeriodMode to " + wpi::Twine{highSemiPeriod ? "true" : "false"});
}
void Counter::SetPulseLengthMode(double threshold) {
if (StatusIsFatal()) {
return;
}
int32_t status = 0;
HAL_SetCounterPulseLengthMode(m_counter, threshold, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "SetPulseLengthMode");
}
void Counter::SetReverseDirection(bool reverseDirection) {
if (StatusIsFatal()) {
return;
}
int32_t status = 0;
HAL_SetCounterReverseDirection(m_counter, reverseDirection, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status,
"SetReverseDirection to " +
wpi::Twine{reverseDirection ? "true" : "false"});
}
void Counter::SetSamplesToAverage(int samplesToAverage) {
if (samplesToAverage < 1 || samplesToAverage > 127) {
wpi_setWPIErrorWithContext(
ParameterOutOfRange,
"Average counter values must be between 1 and 127");
throw FRC_MakeError(err::ParameterOutOfRange,
"Average counter values must be between 1 and 127");
}
int32_t status = 0;
HAL_SetCounterSamplesToAverage(m_counter, samplesToAverage, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(
status, "SetSamplesToAverage to " + wpi::Twine{samplesToAverage});
}
int Counter::GetSamplesToAverage() const {
int32_t status = 0;
int samples = HAL_GetCounterSamplesToAverage(m_counter, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "GetSamplesToAverage");
return samples;
}
@@ -309,69 +262,48 @@ int Counter::GetFPGAIndex() const {
}
int Counter::Get() const {
if (StatusIsFatal()) {
return 0;
}
int32_t status = 0;
int value = HAL_GetCounter(m_counter, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Get");
return value;
}
void Counter::Reset() {
if (StatusIsFatal()) {
return;
}
int32_t status = 0;
HAL_ResetCounter(m_counter, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Reset");
}
double Counter::GetPeriod() const {
if (StatusIsFatal()) {
return 0.0;
}
int32_t status = 0;
double value = HAL_GetCounterPeriod(m_counter, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "GetPeriod");
return value;
}
void Counter::SetMaxPeriod(double maxPeriod) {
if (StatusIsFatal()) {
return;
}
int32_t status = 0;
HAL_SetCounterMaxPeriod(m_counter, maxPeriod, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "SetMaxPeriod");
}
void Counter::SetUpdateWhenEmpty(bool enabled) {
if (StatusIsFatal()) {
return;
}
int32_t status = 0;
HAL_SetCounterUpdateWhenEmpty(m_counter, enabled, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "SetUpdateWhenEmpty");
}
bool Counter::GetStopped() const {
if (StatusIsFatal()) {
return false;
}
int32_t status = 0;
bool value = HAL_GetCounterStopped(m_counter, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "GetStopped");
return value;
}
bool Counter::GetDirection() const {
if (StatusIsFatal()) {
return false;
}
int32_t status = 0;
bool value = HAL_GetCounterDirection(m_counter, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "GetDirection");
return value;
}

View File

@@ -4,21 +4,22 @@
#include "frc/DMA.h"
#include <frc/AnalogInput.h>
#include <frc/Counter.h>
#include <frc/DigitalSource.h>
#include <frc/DutyCycle.h>
#include <frc/Encoder.h>
#include <hal/DMA.h>
#include <hal/HALBase.h>
#include "frc/AnalogInput.h"
#include "frc/Counter.h"
#include "frc/DigitalSource.h"
#include "frc/DutyCycle.h"
#include "frc/Encoder.h"
#include "frc/Errors.h"
using namespace frc;
DMA::DMA() {
int32_t status = 0;
dmaHandle = HAL_InitializeDMA(&status);
wpi_setErrorWithContext(status, HAL_GetErrorMessage(status));
FRC_CheckErrorStatus(status, "InitializeDMA");
}
DMA::~DMA() {
@@ -28,68 +29,68 @@ DMA::~DMA() {
void DMA::SetPause(bool pause) {
int32_t status = 0;
HAL_SetDMAPause(dmaHandle, pause, &status);
wpi_setErrorWithContext(status, HAL_GetErrorMessage(status));
FRC_CheckErrorStatus(status, "SetPause");
}
void DMA::SetRate(int cycles) {
int32_t status = 0;
HAL_SetDMARate(dmaHandle, cycles, &status);
wpi_setErrorWithContext(status, HAL_GetErrorMessage(status));
FRC_CheckErrorStatus(status, "SetRate");
}
void DMA::AddEncoder(const Encoder* encoder) {
int32_t status = 0;
HAL_AddDMAEncoder(dmaHandle, encoder->m_encoder, &status);
wpi_setErrorWithContext(status, HAL_GetErrorMessage(status));
FRC_CheckErrorStatus(status, "AddEncoder");
}
void DMA::AddEncoderPeriod(const Encoder* encoder) {
int32_t status = 0;
HAL_AddDMAEncoderPeriod(dmaHandle, encoder->m_encoder, &status);
wpi_setErrorWithContext(status, HAL_GetErrorMessage(status));
FRC_CheckErrorStatus(status, "AddEncoderPeriod");
}
void DMA::AddCounter(const Counter* counter) {
int32_t status = 0;
HAL_AddDMACounter(dmaHandle, counter->m_counter, &status);
wpi_setErrorWithContext(status, HAL_GetErrorMessage(status));
FRC_CheckErrorStatus(status, "AddCounter");
}
void DMA::AddCounterPeriod(const Counter* counter) {
int32_t status = 0;
HAL_AddDMACounterPeriod(dmaHandle, counter->m_counter, &status);
wpi_setErrorWithContext(status, HAL_GetErrorMessage(status));
FRC_CheckErrorStatus(status, "AddCounterPeriod");
}
void DMA::AddDigitalSource(const DigitalSource* digitalSource) {
int32_t status = 0;
HAL_AddDMADigitalSource(dmaHandle, digitalSource->GetPortHandleForRouting(),
&status);
wpi_setErrorWithContext(status, HAL_GetErrorMessage(status));
FRC_CheckErrorStatus(status, "AddDigitalSource");
}
void DMA::AddDutyCycle(const DutyCycle* dutyCycle) {
int32_t status = 0;
HAL_AddDMADutyCycle(dmaHandle, dutyCycle->m_handle, &status);
wpi_setErrorWithContext(status, HAL_GetErrorMessage(status));
FRC_CheckErrorStatus(status, "AddDutyCycle");
}
void DMA::AddAnalogInput(const AnalogInput* analogInput) {
int32_t status = 0;
HAL_AddDMAAnalogInput(dmaHandle, analogInput->m_port, &status);
wpi_setErrorWithContext(status, HAL_GetErrorMessage(status));
FRC_CheckErrorStatus(status, "AddAnalogInput");
}
void DMA::AddAveragedAnalogInput(const AnalogInput* analogInput) {
int32_t status = 0;
HAL_AddDMAAveragedAnalogInput(dmaHandle, analogInput->m_port, &status);
wpi_setErrorWithContext(status, HAL_GetErrorMessage(status));
FRC_CheckErrorStatus(status, "AddAveragedAnalogInput");
}
void DMA::AddAnalogAccumulator(const AnalogInput* analogInput) {
int32_t status = 0;
HAL_AddDMAAnalogAccumulator(dmaHandle, analogInput->m_port, &status);
wpi_setErrorWithContext(status, HAL_GetErrorMessage(status));
FRC_CheckErrorStatus(status, "AddAnalogAccumulator");
}
void DMA::SetExternalTrigger(DigitalSource* source, bool rising, bool falling) {
@@ -98,17 +99,17 @@ void DMA::SetExternalTrigger(DigitalSource* source, bool rising, bool falling) {
static_cast<HAL_AnalogTriggerType>(
source->GetAnalogTriggerTypeForRouting()),
rising, falling, &status);
wpi_setErrorWithContext(status, HAL_GetErrorMessage(status));
FRC_CheckErrorStatus(status, "SetExternalTrigger");
}
void DMA::StartDMA(int queueDepth) {
int32_t status = 0;
HAL_StartDMA(dmaHandle, queueDepth, &status);
wpi_setErrorWithContext(status, HAL_GetErrorMessage(status));
FRC_CheckErrorStatus(status, "StartDMA");
}
void DMA::StopDMA() {
int32_t status = 0;
HAL_StopDMA(dmaHandle, &status);
wpi_setErrorWithContext(status, HAL_GetErrorMessage(status));
FRC_CheckErrorStatus(status, "StopDMA");
}

View File

@@ -14,9 +14,9 @@
#include "frc/Counter.h"
#include "frc/Encoder.h"
#include "frc/Errors.h"
#include "frc/SensorUtil.h"
#include "frc/Utility.h"
#include "frc/WPIErrors.h"
#include "frc/smartdashboard/SendableRegistry.h"
using namespace frc;
@@ -29,7 +29,7 @@ DigitalGlitchFilter::DigitalGlitchFilter() {
std::scoped_lock lock(m_mutex);
auto index =
std::find(m_filterAllocated.begin(), m_filterAllocated.end(), false);
wpi_assert(index != m_filterAllocated.end());
FRC_Assert(index != m_filterAllocated.end());
m_channelIndex = std::distance(m_filterAllocated.begin(), index);
*index = true;
@@ -48,12 +48,11 @@ DigitalGlitchFilter::~DigitalGlitchFilter() {
}
DigitalGlitchFilter::DigitalGlitchFilter(DigitalGlitchFilter&& rhs)
: ErrorBase(std::move(rhs)), SendableHelper(std::move(rhs)) {
: SendableHelper(std::move(rhs)) {
std::swap(m_channelIndex, rhs.m_channelIndex);
}
DigitalGlitchFilter& DigitalGlitchFilter::operator=(DigitalGlitchFilter&& rhs) {
ErrorBase::operator=(std::move(rhs));
SendableHelper::operator=(std::move(rhs));
std::swap(m_channelIndex, rhs.m_channelIndex);
@@ -71,35 +70,31 @@ void DigitalGlitchFilter::DoAdd(DigitalSource* input, int requestedIndex) {
if (input) {
// We don't support GlitchFilters on AnalogTriggers.
if (input->IsAnalogTrigger()) {
wpi_setErrorWithContext(
throw FRC_MakeError(
-1, "Analog Triggers not supported for DigitalGlitchFilters");
return;
}
int32_t status = 0;
HAL_SetFilterSelect(input->GetPortHandleForRouting(), requestedIndex,
&status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status,
"requested index " + wpi::Twine{requestedIndex});
// Validate that we set it correctly.
int actualIndex =
HAL_GetFilterSelect(input->GetPortHandleForRouting(), &status);
wpi_assertEqual(actualIndex, requestedIndex);
FRC_CheckErrorStatus(status,
"requested index " + wpi::Twine{requestedIndex});
FRC_Assert(actualIndex == requestedIndex);
}
}
void DigitalGlitchFilter::Add(Encoder* input) {
Add(input->m_aSource.get());
if (StatusIsFatal()) {
return;
}
Add(input->m_bSource.get());
}
void DigitalGlitchFilter::Add(Counter* input) {
Add(input->m_upSource.get());
if (StatusIsFatal()) {
return;
}
Add(input->m_downSource.get());
}
@@ -109,24 +104,18 @@ void DigitalGlitchFilter::Remove(DigitalSource* input) {
void DigitalGlitchFilter::Remove(Encoder* input) {
Remove(input->m_aSource.get());
if (StatusIsFatal()) {
return;
}
Remove(input->m_bSource.get());
}
void DigitalGlitchFilter::Remove(Counter* input) {
Remove(input->m_upSource.get());
if (StatusIsFatal()) {
return;
}
Remove(input->m_downSource.get());
}
void DigitalGlitchFilter::SetPeriodCycles(int fpgaCycles) {
int32_t status = 0;
HAL_SetFilterPeriod(m_channelIndex, fpgaCycles, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Channel " + wpi::Twine{m_channelIndex});
}
void DigitalGlitchFilter::SetPeriodNanoSeconds(uint64_t nanoseconds) {
@@ -134,25 +123,20 @@ void DigitalGlitchFilter::SetPeriodNanoSeconds(uint64_t nanoseconds) {
int fpgaCycles =
nanoseconds * HAL_GetSystemClockTicksPerMicrosecond() / 4 / 1000;
HAL_SetFilterPeriod(m_channelIndex, fpgaCycles, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Channel " + wpi::Twine{m_channelIndex});
}
int DigitalGlitchFilter::GetPeriodCycles() {
int32_t status = 0;
int fpgaCycles = HAL_GetFilterPeriod(m_channelIndex, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Channel " + wpi::Twine{m_channelIndex});
return fpgaCycles;
}
uint64_t DigitalGlitchFilter::GetPeriodNanoSeconds() {
int32_t status = 0;
int fpgaCycles = HAL_GetFilterPeriod(m_channelIndex, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Channel " + wpi::Twine{m_channelIndex});
return static_cast<uint64_t>(fpgaCycles) * 1000L /
static_cast<uint64_t>(HAL_GetSystemClockTicksPerMicrosecond() / 4);
}

View File

@@ -4,15 +4,17 @@
#include "frc/DigitalInput.h"
#include <iostream>
#include <limits>
#include <hal/DIO.h>
#include <hal/FRCUsageReporting.h>
#include <hal/HALBase.h>
#include <hal/Ports.h>
#include <wpi/StackTrace.h>
#include "frc/Errors.h"
#include "frc/SensorUtil.h"
#include "frc/WPIErrors.h"
#include "frc/smartdashboard/SendableBuilder.h"
#include "frc/smartdashboard/SendableRegistry.h"
@@ -20,40 +22,29 @@ using namespace frc;
DigitalInput::DigitalInput(int channel) {
if (!SensorUtil::CheckDigitalChannel(channel)) {
wpi_setWPIErrorWithContext(ChannelIndexOutOfRange,
"Digital Channel " + wpi::Twine(channel));
m_channel = std::numeric_limits<int>::max();
return;
throw FRC_MakeError(err::ChannelIndexOutOfRange,
"Digital Channel " + wpi::Twine{channel});
}
m_channel = channel;
int32_t status = 0;
m_handle = HAL_InitializeDIOPort(HAL_GetPort(channel), true, &status);
if (status != 0) {
wpi_setHALErrorWithRange(status, 0, HAL_GetNumDigitalChannels(), channel);
m_handle = HAL_kInvalidHandle;
m_channel = std::numeric_limits<int>::max();
return;
}
std::string stackTrace = wpi::GetStackTrace(1);
m_handle = HAL_InitializeDIOPort(HAL_GetPort(channel), true,
stackTrace.c_str(), &status);
FRC_CheckErrorStatus(status, "Digital Channel " + wpi::Twine{channel});
HAL_Report(HALUsageReporting::kResourceType_DigitalInput, channel + 1);
SendableRegistry::GetInstance().AddLW(this, "DigitalInput", channel);
}
DigitalInput::~DigitalInput() {
if (StatusIsFatal()) {
return;
}
HAL_FreeDIOPort(m_handle);
}
bool DigitalInput::Get() const {
if (StatusIsFatal()) {
return false;
}
int32_t status = 0;
bool value = HAL_GetDIO(m_handle, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Get");
return value;
}

View File

@@ -10,9 +10,10 @@
#include <hal/FRCUsageReporting.h>
#include <hal/HALBase.h>
#include <hal/Ports.h>
#include <wpi/StackTrace.h>
#include "frc/Errors.h"
#include "frc/SensorUtil.h"
#include "frc/WPIErrors.h"
#include "frc/smartdashboard/SendableBuilder.h"
#include "frc/smartdashboard/SendableRegistry.h"
@@ -21,54 +22,42 @@ using namespace frc;
DigitalOutput::DigitalOutput(int channel) {
m_pwmGenerator = HAL_kInvalidHandle;
if (!SensorUtil::CheckDigitalChannel(channel)) {
wpi_setWPIErrorWithContext(ChannelIndexOutOfRange,
"Digital Channel " + wpi::Twine(channel));
m_channel = std::numeric_limits<int>::max();
return;
throw FRC_MakeError(err::ChannelIndexOutOfRange,
"Digital Channel " + wpi::Twine{channel});
}
m_channel = channel;
int32_t status = 0;
m_handle = HAL_InitializeDIOPort(HAL_GetPort(channel), false, &status);
if (status != 0) {
wpi_setHALErrorWithRange(status, 0, HAL_GetNumDigitalChannels(), channel);
m_channel = std::numeric_limits<int>::max();
m_handle = HAL_kInvalidHandle;
return;
}
std::string stackTrace = wpi::GetStackTrace(1);
m_handle = HAL_InitializeDIOPort(HAL_GetPort(channel), false,
stackTrace.c_str(), &status);
FRC_CheckErrorStatus(status, "Digital Channel " + wpi::Twine{channel});
HAL_Report(HALUsageReporting::kResourceType_DigitalOutput, channel + 1);
SendableRegistry::GetInstance().AddLW(this, "DigitalOutput", channel);
}
DigitalOutput::~DigitalOutput() {
if (StatusIsFatal()) {
return;
}
// Disable the PWM in case it was running.
DisablePWM();
try {
DisablePWM();
} catch (const RuntimeError& e) {
e.Report();
}
HAL_FreeDIOPort(m_handle);
}
void DigitalOutput::Set(bool value) {
if (StatusIsFatal()) {
return;
}
int32_t status = 0;
HAL_SetDIO(m_handle, value, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Digital Channel " + wpi::Twine{m_channel});
}
bool DigitalOutput::Get() const {
if (StatusIsFatal()) {
return false;
}
int32_t status = 0;
bool val = HAL_GetDIO(m_handle, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Digital Channel " + wpi::Twine{m_channel});
return val;
}
@@ -89,34 +78,22 @@ int DigitalOutput::GetChannel() const {
}
void DigitalOutput::Pulse(double length) {
if (StatusIsFatal()) {
return;
}
int32_t status = 0;
HAL_Pulse(m_handle, length, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Digital Channel " + wpi::Twine{m_channel});
}
bool DigitalOutput::IsPulsing() const {
if (StatusIsFatal()) {
return false;
}
int32_t status = 0;
bool value = HAL_IsPulsing(m_handle, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Digital Channel " + wpi::Twine{m_channel});
return value;
}
void DigitalOutput::SetPWMRate(double rate) {
if (StatusIsFatal()) {
return;
}
int32_t status = 0;
HAL_SetDigitalPWMRate(rate, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Digital Channel " + wpi::Twine{m_channel});
}
void DigitalOutput::EnablePWM(double initialDutyCycle) {
@@ -126,29 +103,17 @@ void DigitalOutput::EnablePWM(double initialDutyCycle) {
int32_t status = 0;
if (StatusIsFatal()) {
return;
}
m_pwmGenerator = HAL_AllocateDigitalPWM(&status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Digital Channel " + wpi::Twine{m_channel});
if (StatusIsFatal()) {
return;
}
HAL_SetDigitalPWMDutyCycle(m_pwmGenerator, initialDutyCycle, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Digital Channel " + wpi::Twine{m_channel});
if (StatusIsFatal()) {
return;
}
HAL_SetDigitalPWMOutputChannel(m_pwmGenerator, m_channel, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Digital Channel " + wpi::Twine{m_channel});
}
void DigitalOutput::DisablePWM() {
if (StatusIsFatal()) {
return;
}
if (m_pwmGenerator == HAL_kInvalidHandle) {
return;
}
@@ -158,22 +123,18 @@ void DigitalOutput::DisablePWM() {
// Disable the output by routing to a dead bit.
HAL_SetDigitalPWMOutputChannel(m_pwmGenerator, SensorUtil::kDigitalChannels,
&status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Digital Channel " + wpi::Twine{m_channel});
HAL_FreeDigitalPWM(m_pwmGenerator, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Digital Channel " + wpi::Twine{m_channel});
m_pwmGenerator = HAL_kInvalidHandle;
}
void DigitalOutput::UpdateDutyCycle(double dutyCycle) {
if (StatusIsFatal()) {
return;
}
int32_t status = 0;
HAL_SetDigitalPWMDutyCycle(m_pwmGenerator, dutyCycle, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Digital Channel " + wpi::Twine{m_channel});
}
void DigitalOutput::SetSimDevice(HAL_SimDeviceHandle device) {

View File

@@ -11,8 +11,8 @@
#include <hal/Ports.h>
#include <hal/Solenoid.h>
#include "frc/Errors.h"
#include "frc/SensorUtil.h"
#include "frc/WPIErrors.h"
#include "frc/smartdashboard/SendableBuilder.h"
#include "frc/smartdashboard/SendableRegistry.h"
@@ -28,42 +28,31 @@ DoubleSolenoid::DoubleSolenoid(int moduleNumber, int forwardChannel,
m_forwardChannel(forwardChannel),
m_reverseChannel(reverseChannel) {
if (!SensorUtil::CheckSolenoidModule(m_moduleNumber)) {
wpi_setWPIErrorWithContext(ModuleIndexOutOfRange,
"Solenoid Module " + wpi::Twine(m_moduleNumber));
return;
throw FRC_MakeError(err::ModuleIndexOutOfRange,
"Solenoid Module " + wpi::Twine{m_moduleNumber});
}
if (!SensorUtil::CheckSolenoidChannel(m_forwardChannel)) {
wpi_setWPIErrorWithContext(
ChannelIndexOutOfRange,
"Solenoid Channel " + wpi::Twine(m_forwardChannel));
return;
throw FRC_MakeError(err::ChannelIndexOutOfRange,
"Solenoid Channel " + wpi::Twine{m_forwardChannel});
}
if (!SensorUtil::CheckSolenoidChannel(m_reverseChannel)) {
wpi_setWPIErrorWithContext(
ChannelIndexOutOfRange,
"Solenoid Channel " + wpi::Twine(m_reverseChannel));
return;
throw FRC_MakeError(err::ChannelIndexOutOfRange,
"Solenoid Channel " + wpi::Twine{m_reverseChannel});
}
int32_t status = 0;
m_forwardHandle = HAL_InitializeSolenoidPort(
HAL_GetPortWithModule(moduleNumber, m_forwardChannel), &status);
if (status != 0) {
wpi_setHALErrorWithRange(status, 0, HAL_GetNumSolenoidChannels(),
forwardChannel);
m_forwardHandle = HAL_kInvalidHandle;
m_reverseHandle = HAL_kInvalidHandle;
return;
}
FRC_CheckErrorStatus(status, "Solenoid Module " + wpi::Twine{m_moduleNumber} +
" Channel " + wpi::Twine{m_forwardChannel});
m_reverseHandle = HAL_InitializeSolenoidPort(
HAL_GetPortWithModule(moduleNumber, m_reverseChannel), &status);
if (status != 0) {
wpi_setHALErrorWithRange(status, 0, HAL_GetNumSolenoidChannels(),
reverseChannel);
// free forward solenoid
HAL_FreeSolenoidPort(m_forwardHandle);
m_forwardHandle = HAL_kInvalidHandle;
m_reverseHandle = HAL_kInvalidHandle;
FRC_CheckErrorStatus(status, "Solenoid Module " +
wpi::Twine{m_moduleNumber} + " Channel " +
wpi::Twine{m_reverseChannel});
return;
}
@@ -85,10 +74,6 @@ DoubleSolenoid::~DoubleSolenoid() {
}
void DoubleSolenoid::Set(Value value) {
if (StatusIsFatal()) {
return;
}
bool forward = false;
bool reverse = false;
@@ -112,22 +97,26 @@ void DoubleSolenoid::Set(Value value) {
int rstatus = 0;
HAL_SetSolenoid(m_reverseHandle, reverse, &rstatus);
wpi_setHALError(fstatus);
wpi_setHALError(rstatus);
FRC_CheckErrorStatus(fstatus, "Solenoid Module " +
wpi::Twine{m_moduleNumber} + " Channel " +
wpi::Twine{m_forwardChannel});
FRC_CheckErrorStatus(rstatus, "Solenoid Module " +
wpi::Twine{m_moduleNumber} + " Channel " +
wpi::Twine{m_reverseChannel});
}
DoubleSolenoid::Value DoubleSolenoid::Get() const {
if (StatusIsFatal()) {
return kOff;
}
int fstatus = 0;
int rstatus = 0;
bool valueForward = HAL_GetSolenoid(m_forwardHandle, &fstatus);
bool valueReverse = HAL_GetSolenoid(m_reverseHandle, &rstatus);
wpi_setHALError(fstatus);
wpi_setHALError(rstatus);
FRC_CheckErrorStatus(fstatus, "Solenoid Module " +
wpi::Twine{m_moduleNumber} + " Channel " +
wpi::Twine{m_forwardChannel});
FRC_CheckErrorStatus(rstatus, "Solenoid Module " +
wpi::Twine{m_moduleNumber} + " Channel " +
wpi::Twine{m_reverseChannel});
if (valueForward) {
return kForward;

View File

@@ -17,9 +17,9 @@
#include <wpi/SmallString.h>
#include <wpi/StringRef.h>
#include "frc/Errors.h"
#include "frc/MotorSafety.h"
#include "frc/Timer.h"
#include "frc/WPIErrors.h"
namespace frc {
// A simple class which caches the previous value written to an NT entry
@@ -140,7 +140,8 @@ void DriverStation::ReportError(bool isError, int32_t code,
bool DriverStation::GetStickButton(int stick, int button) {
if (stick < 0 || stick >= kJoystickPorts) {
wpi_setWPIError(BadJoystickIndex);
FRC_ReportError(warn::BadJoystickIndex,
"stick " + wpi::Twine{stick} + " out of range");
return false;
}
if (button <= 0) {
@@ -163,7 +164,8 @@ bool DriverStation::GetStickButton(int stick, int button) {
bool DriverStation::GetStickButtonPressed(int stick, int button) {
if (stick < 0 || stick >= kJoystickPorts) {
wpi_setWPIError(BadJoystickIndex);
FRC_ReportError(warn::BadJoystickIndex,
"stick " + wpi::Twine{stick} + " out of range");
return false;
}
if (button <= 0) {
@@ -192,7 +194,8 @@ bool DriverStation::GetStickButtonPressed(int stick, int button) {
bool DriverStation::GetStickButtonReleased(int stick, int button) {
if (stick < 0 || stick >= kJoystickPorts) {
wpi_setWPIError(BadJoystickIndex);
FRC_ReportError(warn::BadJoystickIndex,
"stick " + wpi::Twine{stick} + " out of range");
return false;
}
if (button <= 0) {
@@ -221,11 +224,13 @@ bool DriverStation::GetStickButtonReleased(int stick, int button) {
double DriverStation::GetStickAxis(int stick, int axis) {
if (stick < 0 || stick >= kJoystickPorts) {
wpi_setWPIError(BadJoystickIndex);
FRC_ReportError(warn::BadJoystickIndex,
"stick " + wpi::Twine{stick} + " out of range");
return 0.0;
}
if (axis < 0 || axis >= HAL_kMaxJoystickAxes) {
wpi_setWPIError(BadJoystickAxis);
FRC_ReportError(warn::BadJoystickAxis,
"axis " + wpi::Twine{axis} + " out of range");
return 0.0;
}
@@ -243,11 +248,13 @@ double DriverStation::GetStickAxis(int stick, int axis) {
int DriverStation::GetStickPOV(int stick, int pov) {
if (stick < 0 || stick >= kJoystickPorts) {
wpi_setWPIError(BadJoystickIndex);
FRC_ReportError(warn::BadJoystickIndex,
"stick " + wpi::Twine{stick} + " out of range");
return -1;
}
if (pov < 0 || pov >= HAL_kMaxJoystickPOVs) {
wpi_setWPIError(BadJoystickAxis);
FRC_ReportError(warn::BadJoystickAxis,
"POV " + wpi::Twine{pov} + " out of range");
return -1;
}
@@ -265,7 +272,8 @@ int DriverStation::GetStickPOV(int stick, int pov) {
int DriverStation::GetStickButtons(int stick) const {
if (stick < 0 || stick >= kJoystickPorts) {
wpi_setWPIError(BadJoystickIndex);
FRC_ReportError(warn::BadJoystickIndex,
"stick " + wpi::Twine{stick} + " out of range");
return 0;
}
@@ -277,7 +285,8 @@ int DriverStation::GetStickButtons(int stick) const {
int DriverStation::GetStickAxisCount(int stick) const {
if (stick < 0 || stick >= kJoystickPorts) {
wpi_setWPIError(BadJoystickIndex);
FRC_ReportError(warn::BadJoystickIndex,
"stick " + wpi::Twine{stick} + " out of range");
return 0;
}
@@ -289,7 +298,8 @@ int DriverStation::GetStickAxisCount(int stick) const {
int DriverStation::GetStickPOVCount(int stick) const {
if (stick < 0 || stick >= kJoystickPorts) {
wpi_setWPIError(BadJoystickIndex);
FRC_ReportError(warn::BadJoystickIndex,
"stick " + wpi::Twine{stick} + " out of range");
return 0;
}
@@ -301,7 +311,8 @@ int DriverStation::GetStickPOVCount(int stick) const {
int DriverStation::GetStickButtonCount(int stick) const {
if (stick < 0 || stick >= kJoystickPorts) {
wpi_setWPIError(BadJoystickIndex);
FRC_ReportError(warn::BadJoystickIndex,
"stick " + wpi::Twine{stick} + " out of range");
return 0;
}
@@ -313,7 +324,8 @@ int DriverStation::GetStickButtonCount(int stick) const {
bool DriverStation::GetJoystickIsXbox(int stick) const {
if (stick < 0 || stick >= kJoystickPorts) {
wpi_setWPIError(BadJoystickIndex);
FRC_ReportError(warn::BadJoystickIndex,
"stick " + wpi::Twine{stick} + " out of range");
return false;
}
@@ -325,7 +337,8 @@ bool DriverStation::GetJoystickIsXbox(int stick) const {
int DriverStation::GetJoystickType(int stick) const {
if (stick < 0 || stick >= kJoystickPorts) {
wpi_setWPIError(BadJoystickIndex);
FRC_ReportError(warn::BadJoystickIndex,
"stick " + wpi::Twine{stick} + " out of range");
return -1;
}
@@ -337,7 +350,8 @@ int DriverStation::GetJoystickType(int stick) const {
std::string DriverStation::GetJoystickName(int stick) const {
if (stick < 0 || stick >= kJoystickPorts) {
wpi_setWPIError(BadJoystickIndex);
FRC_ReportError(warn::BadJoystickIndex,
"stick " + wpi::Twine{stick} + " out of range");
}
HAL_JoystickDescriptor descriptor;
@@ -348,7 +362,8 @@ std::string DriverStation::GetJoystickName(int stick) const {
int DriverStation::GetJoystickAxisType(int stick, int axis) const {
if (stick < 0 || stick >= kJoystickPorts) {
wpi_setWPIError(BadJoystickIndex);
FRC_ReportError(warn::BadJoystickIndex,
"stick " + wpi::Twine{stick} + " out of range");
return -1;
}
@@ -537,7 +552,7 @@ double DriverStation::GetMatchTime() const {
double DriverStation::GetBatteryVoltage() const {
int32_t status = 0;
double voltage = HAL_GetVinVoltage(&status);
wpi_setErrorWithContext(status, "getVinVoltage");
FRC_CheckErrorStatus(status, "getVinVoltage");
return voltage;
}

View File

@@ -9,18 +9,17 @@
#include "frc/Base.h"
#include "frc/DigitalSource.h"
#include "frc/WPIErrors.h"
#include "frc/Errors.h"
#include "frc/smartdashboard/SendableBuilder.h"
using namespace frc;
DutyCycle::DutyCycle(DigitalSource* source)
: m_source{source, NullDeleter<DigitalSource>()} {
if (m_source == nullptr) {
wpi_setWPIError(NullParameter);
} else {
InitDutyCycle();
if (!m_source) {
throw FRC_MakeError(err::NullParameter, "source");
}
InitDutyCycle();
}
DutyCycle::DutyCycle(DigitalSource& source)
@@ -30,11 +29,10 @@ DutyCycle::DutyCycle(DigitalSource& source)
DutyCycle::DutyCycle(std::shared_ptr<DigitalSource> source)
: m_source{std::move(source)} {
if (m_source == nullptr) {
wpi_setWPIError(NullParameter);
} else {
InitDutyCycle();
if (!m_source) {
throw FRC_MakeError(err::NullParameter, "source");
}
InitDutyCycle();
}
DutyCycle::~DutyCycle() {
@@ -48,7 +46,7 @@ void DutyCycle::InitDutyCycle() {
static_cast<HAL_AnalogTriggerType>(
m_source->GetAnalogTriggerTypeForRouting()),
&status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "InitDutyCycle");
int index = GetFPGAIndex();
HAL_Report(HALUsageReporting::kResourceType_DutyCycle, index + 1);
SendableRegistry::GetInstance().AddLW(this, "Duty Cycle", index);
@@ -57,35 +55,35 @@ void DutyCycle::InitDutyCycle() {
int DutyCycle::GetFPGAIndex() const {
int32_t status = 0;
auto retVal = HAL_GetDutyCycleFPGAIndex(m_handle, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "GetFPGAIndex");
return retVal;
}
int DutyCycle::GetFrequency() const {
int32_t status = 0;
auto retVal = HAL_GetDutyCycleFrequency(m_handle, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "GetFrequency");
return retVal;
}
double DutyCycle::GetOutput() const {
int32_t status = 0;
auto retVal = HAL_GetDutyCycleOutput(m_handle, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "GetOutput");
return retVal;
}
unsigned int DutyCycle::GetOutputRaw() const {
int32_t status = 0;
auto retVal = HAL_GetDutyCycleOutputRaw(m_handle, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "GetOutputRaw");
return retVal;
}
unsigned int DutyCycle::GetOutputScaleFactor() const {
int32_t status = 0;
auto retVal = HAL_GetDutyCycleOutputScaleFactor(m_handle, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "GetOutputScaleFactor");
return retVal;
}

View File

@@ -11,7 +11,7 @@
#include "frc/Base.h"
#include "frc/DigitalInput.h"
#include "frc/WPIErrors.h"
#include "frc/Errors.h"
#include "frc/smartdashboard/SendableBuilder.h"
#include "frc/smartdashboard/SendableRegistry.h"
@@ -31,11 +31,13 @@ Encoder::Encoder(DigitalSource* aSource, DigitalSource* bSource,
bool reverseDirection, EncodingType encodingType)
: m_aSource(aSource, NullDeleter<DigitalSource>()),
m_bSource(bSource, NullDeleter<DigitalSource>()) {
if (m_aSource == nullptr || m_bSource == nullptr) {
wpi_setWPIError(NullParameter);
} else {
InitEncoder(reverseDirection, encodingType);
if (!m_aSource) {
throw FRC_MakeError(err::NullParameter, "aSource");
}
if (!m_bSource) {
throw FRC_MakeError(err::NullParameter, "bSource");
}
InitEncoder(reverseDirection, encodingType);
}
Encoder::Encoder(DigitalSource& aSource, DigitalSource& bSource,
@@ -49,184 +51,133 @@ Encoder::Encoder(std::shared_ptr<DigitalSource> aSource,
std::shared_ptr<DigitalSource> bSource, bool reverseDirection,
EncodingType encodingType)
: m_aSource(std::move(aSource)), m_bSource(std::move(bSource)) {
if (m_aSource == nullptr || m_bSource == nullptr) {
wpi_setWPIError(NullParameter);
} else {
InitEncoder(reverseDirection, encodingType);
if (!m_aSource) {
throw FRC_MakeError(err::NullParameter, "aSource");
}
if (!m_bSource) {
throw FRC_MakeError(err::NullParameter, "bSource");
}
InitEncoder(reverseDirection, encodingType);
}
Encoder::~Encoder() {
int32_t status = 0;
HAL_FreeEncoder(m_encoder, &status);
wpi_setHALError(status);
FRC_ReportError(status, "FreeEncoder");
}
int Encoder::Get() const {
if (StatusIsFatal()) {
return 0;
}
int32_t status = 0;
int value = HAL_GetEncoder(m_encoder, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Get");
return value;
}
void Encoder::Reset() {
if (StatusIsFatal()) {
return;
}
int32_t status = 0;
HAL_ResetEncoder(m_encoder, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Reset");
}
double Encoder::GetPeriod() const {
if (StatusIsFatal()) {
return 0.0;
}
int32_t status = 0;
double value = HAL_GetEncoderPeriod(m_encoder, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "GetPeriod");
return value;
}
void Encoder::SetMaxPeriod(double maxPeriod) {
if (StatusIsFatal()) {
return;
}
int32_t status = 0;
HAL_SetEncoderMaxPeriod(m_encoder, maxPeriod, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "SetMaxPeriod");
}
bool Encoder::GetStopped() const {
if (StatusIsFatal()) {
return true;
}
int32_t status = 0;
bool value = HAL_GetEncoderStopped(m_encoder, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "GetStopped");
return value;
}
bool Encoder::GetDirection() const {
if (StatusIsFatal()) {
return false;
}
int32_t status = 0;
bool value = HAL_GetEncoderDirection(m_encoder, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "GetDirection");
return value;
}
int Encoder::GetRaw() const {
if (StatusIsFatal()) {
return 0;
}
int32_t status = 0;
int value = HAL_GetEncoderRaw(m_encoder, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "GetRaw");
return value;
}
int Encoder::GetEncodingScale() const {
int32_t status = 0;
int val = HAL_GetEncoderEncodingScale(m_encoder, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "GetEncodingScale");
return val;
}
double Encoder::GetDistance() const {
if (StatusIsFatal()) {
return 0.0;
}
int32_t status = 0;
double value = HAL_GetEncoderDistance(m_encoder, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "GetDistance");
return value;
}
double Encoder::GetRate() const {
if (StatusIsFatal()) {
return 0.0;
}
int32_t status = 0;
double value = HAL_GetEncoderRate(m_encoder, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "GetRate");
return value;
}
void Encoder::SetMinRate(double minRate) {
if (StatusIsFatal()) {
return;
}
int32_t status = 0;
HAL_SetEncoderMinRate(m_encoder, minRate, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "SetMinRate");
}
void Encoder::SetDistancePerPulse(double distancePerPulse) {
if (StatusIsFatal()) {
return;
}
int32_t status = 0;
HAL_SetEncoderDistancePerPulse(m_encoder, distancePerPulse, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "SetDistancePerPulse");
}
double Encoder::GetDistancePerPulse() const {
if (StatusIsFatal()) {
return 0.0;
}
int32_t status = 0;
double distancePerPulse = HAL_GetEncoderDistancePerPulse(m_encoder, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "GetDistancePerPulse");
return distancePerPulse;
}
void Encoder::SetReverseDirection(bool reverseDirection) {
if (StatusIsFatal()) {
return;
}
int32_t status = 0;
HAL_SetEncoderReverseDirection(m_encoder, reverseDirection, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "SetReverseDirection");
}
void Encoder::SetSamplesToAverage(int samplesToAverage) {
if (samplesToAverage < 1 || samplesToAverage > 127) {
wpi_setWPIErrorWithContext(
ParameterOutOfRange,
"Average counter values must be between 1 and 127");
return;
throw FRC_MakeError(
err::ParameterOutOfRange,
"Average counter values must be between 1 and 127, got " +
wpi::Twine{samplesToAverage});
}
int32_t status = 0;
HAL_SetEncoderSamplesToAverage(m_encoder, samplesToAverage, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "SetSamplesToAverage");
}
int Encoder::GetSamplesToAverage() const {
int32_t status = 0;
int result = HAL_GetEncoderSamplesToAverage(m_encoder, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "GetSamplesToAverage");
return result;
}
double Encoder::PIDGet() {
if (StatusIsFatal()) {
return 0.0;
}
switch (GetPIDSourceType()) {
case PIDSourceType::kDisplacement:
return GetDistance();
case PIDSourceType::kRate:
return GetRate();
default:
return 0.0;
}
}
void Encoder::SetIndexSource(int channel, Encoder::IndexingType type) {
// Force digital input if just given an index
m_indexSource = std::make_shared<DigitalInput>(channel);
@@ -242,7 +193,7 @@ void Encoder::SetIndexSource(const DigitalSource& source,
source.GetAnalogTriggerTypeForRouting()),
static_cast<HAL_EncoderIndexingType>(type),
&status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "SetIndexSource");
}
void Encoder::SetSimDevice(HAL_SimDeviceHandle device) {
@@ -252,14 +203,14 @@ void Encoder::SetSimDevice(HAL_SimDeviceHandle device) {
int Encoder::GetFPGAIndex() const {
int32_t status = 0;
int val = HAL_GetEncoderFPGAIndex(m_encoder, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "GetFPGAIndex");
return val;
}
void Encoder::InitSendable(SendableBuilder& builder) {
int32_t status = 0;
HAL_EncoderEncodingType type = HAL_GetEncoderEncodingType(m_encoder, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "GetEncodingType");
if (type == HAL_EncoderEncodingType::HAL_Encoder_k4X) {
builder.SetSmartDashboardType("Quadrature Encoder");
} else {
@@ -285,7 +236,7 @@ void Encoder::InitEncoder(bool reverseDirection, EncodingType encodingType) {
m_bSource->GetAnalogTriggerTypeForRouting()),
reverseDirection, static_cast<HAL_EncoderEncodingType>(encodingType),
&status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "InitEncoder");
HAL_Report(HALUsageReporting::kResourceType_Encoder, GetFPGAIndex() + 1,
encodingType);
@@ -294,11 +245,8 @@ void Encoder::InitEncoder(bool reverseDirection, EncodingType encodingType) {
}
double Encoder::DecodingScaleFactor() const {
if (StatusIsFatal()) {
return 0.0;
}
int32_t status = 0;
double val = HAL_GetEncoderDecodingScaleFactor(m_encoder, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "DecodingScaleFactor");
return val;
}

View File

@@ -1,108 +0,0 @@
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include "frc/Error.h"
#include <wpi/Path.h>
#include <wpi/StackTrace.h>
#include "frc/Base.h"
#include "frc/DriverStation.h"
#include "frc/Timer.h"
using namespace frc;
Error::Error(Code code, const wpi::Twine& contextMessage,
wpi::StringRef filename, wpi::StringRef function, int lineNumber,
const ErrorBase* originatingObject) {
Set(code, contextMessage, filename, function, lineNumber, originatingObject);
}
bool Error::operator<(const Error& rhs) const {
if (m_code < rhs.m_code) {
return true;
} else if (m_message < rhs.m_message) {
return true;
} else if (m_filename < rhs.m_filename) {
return true;
} else if (m_function < rhs.m_function) {
return true;
} else if (m_lineNumber < rhs.m_lineNumber) {
return true;
} else if (m_originatingObject < rhs.m_originatingObject) {
return true;
} else if (m_timestamp < rhs.m_timestamp) {
return true;
} else {
return false;
}
}
Error::Code Error::GetCode() const {
return m_code;
}
std::string Error::GetMessage() const {
return m_message;
}
std::string Error::GetFilename() const {
return m_filename;
}
std::string Error::GetFunction() const {
return m_function;
}
int Error::GetLineNumber() const {
return m_lineNumber;
}
const ErrorBase* Error::GetOriginatingObject() const {
return m_originatingObject;
}
double Error::GetTimestamp() const {
return m_timestamp;
}
void Error::Set(Code code, const wpi::Twine& contextMessage,
wpi::StringRef filename, wpi::StringRef function,
int lineNumber, const ErrorBase* originatingObject) {
bool report = true;
if (code == m_code && GetTime() - m_timestamp < 1) {
report = false;
}
m_code = code;
m_message = contextMessage.str();
m_filename = filename;
m_function = function;
m_lineNumber = lineNumber;
m_originatingObject = originatingObject;
if (report) {
m_timestamp = GetTime();
Report();
}
}
void Error::Report() {
DriverStation::ReportError(
true, m_code, m_message,
m_function + wpi::Twine(" [") + wpi::sys::path::filename(m_filename) +
wpi::Twine(':') + wpi::Twine(m_lineNumber) + wpi::Twine(']'),
wpi::GetStackTrace(4));
}
void Error::Clear() {
m_code = 0;
m_message = "";
m_filename = "";
m_function = "";
m_lineNumber = 0;
m_originatingObject = nullptr;
m_timestamp = 0.0;
}

View File

@@ -1,198 +0,0 @@
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include "frc/ErrorBase.h"
#include <cerrno>
#include <cstring>
#include <set>
#include <utility>
#include <hal/HALBase.h>
#include <wpi/Format.h>
#include <wpi/SmallString.h>
#include <wpi/mutex.h>
#include <wpi/raw_ostream.h>
#include "frc/Base.h"
using namespace frc;
namespace {
struct GlobalErrors {
wpi::mutex mutex;
std::set<Error> errors;
const Error* lastError{nullptr};
static GlobalErrors& GetInstance();
static void Insert(const Error& error);
static void Insert(Error&& error);
};
} // namespace
GlobalErrors& GlobalErrors::GetInstance() {
static GlobalErrors inst;
return inst;
}
void GlobalErrors::Insert(const Error& error) {
GlobalErrors& inst = GetInstance();
std::scoped_lock lock(inst.mutex);
inst.lastError = &(*inst.errors.insert(error).first);
}
void GlobalErrors::Insert(Error&& error) {
GlobalErrors& inst = GetInstance();
std::scoped_lock lock(inst.mutex);
inst.lastError = &(*inst.errors.insert(std::move(error)).first);
}
ErrorBase::ErrorBase() {
HAL_Initialize(500, 0);
}
Error& ErrorBase::GetError() {
return m_error;
}
const Error& ErrorBase::GetError() const {
return m_error;
}
void ErrorBase::ClearError() const {
m_error.Clear();
}
void ErrorBase::SetErrnoError(const wpi::Twine& contextMessage,
wpi::StringRef filename, wpi::StringRef function,
int lineNumber) const {
wpi::SmallString<128> buf;
wpi::raw_svector_ostream err(buf);
int errNo = errno;
if (errNo == 0) {
err << "OK: ";
} else {
err << std::strerror(errNo) << " (" << wpi::format_hex(errNo, 10, true)
<< "): ";
}
// Set the current error information for this object.
m_error.Set(-1, err.str() + contextMessage, filename, function, lineNumber,
this);
// Update the global error if there is not one already set.
GlobalErrors::Insert(m_error);
}
void ErrorBase::SetImaqError(int success, const wpi::Twine& contextMessage,
wpi::StringRef filename, wpi::StringRef function,
int lineNumber) const {
// If there was an error
if (success <= 0) {
// Set the current error information for this object.
m_error.Set(success, wpi::Twine(success) + ": " + contextMessage, filename,
function, lineNumber, this);
// Update the global error if there is not one already set.
GlobalErrors::Insert(m_error);
}
}
void ErrorBase::SetError(Error::Code code, const wpi::Twine& contextMessage,
wpi::StringRef filename, wpi::StringRef function,
int lineNumber) const {
// If there was an error
if (code != 0) {
// Set the current error information for this object.
m_error.Set(code, contextMessage, filename, function, lineNumber, this);
// Update the global error if there is not one already set.
GlobalErrors::Insert(m_error);
}
}
void ErrorBase::SetErrorRange(Error::Code code, int32_t minRange,
int32_t maxRange, int32_t requestedValue,
const wpi::Twine& contextMessage,
wpi::StringRef filename, wpi::StringRef function,
int lineNumber) const {
// If there was an error
if (code != 0) {
// Set the current error information for this object.
m_error.Set(code,
contextMessage + ", Minimum Value: " + wpi::Twine(minRange) +
", MaximumValue: " + wpi::Twine(maxRange) +
", Requested Value: " + wpi::Twine(requestedValue),
filename, function, lineNumber, this);
// Update the global error if there is not one already set.
GlobalErrors::Insert(m_error);
}
}
void ErrorBase::SetWPIError(const wpi::Twine& errorMessage, Error::Code code,
const wpi::Twine& contextMessage,
wpi::StringRef filename, wpi::StringRef function,
int lineNumber) const {
// Set the current error information for this object.
m_error.Set(code, errorMessage + ": " + contextMessage, filename, function,
lineNumber, this);
// Update the global error if there is not one already set.
GlobalErrors::Insert(m_error);
}
void ErrorBase::CloneError(const ErrorBase& rhs) const {
m_error = rhs.GetError();
}
bool ErrorBase::StatusIsFatal() const {
return m_error.GetCode() < 0;
}
void ErrorBase::SetGlobalError(Error::Code code,
const wpi::Twine& contextMessage,
wpi::StringRef filename, wpi::StringRef function,
int lineNumber) {
// If there was an error
if (code != 0) {
// Set the current error information for this object.
GlobalErrors::Insert(
Error(code, contextMessage, filename, function, lineNumber, nullptr));
}
}
void ErrorBase::SetGlobalWPIError(const wpi::Twine& errorMessage,
const wpi::Twine& contextMessage,
wpi::StringRef filename,
wpi::StringRef function, int lineNumber) {
GlobalErrors::Insert(Error(-1, errorMessage + ": " + contextMessage, filename,
function, lineNumber, nullptr));
}
Error ErrorBase::GetGlobalError() {
auto& inst = GlobalErrors::GetInstance();
std::scoped_lock mutex(inst.mutex);
if (!inst.lastError) {
return {};
}
return *inst.lastError;
}
std::vector<Error> ErrorBase::GetGlobalErrors() {
auto& inst = GlobalErrors::GetInstance();
std::scoped_lock mutex(inst.mutex);
std::vector<Error> rv;
for (auto&& error : inst.errors) {
rv.push_back(error);
}
return rv;
}
void ErrorBase::ClearGlobalErrors() {
auto& inst = GlobalErrors::GetInstance();
std::scoped_lock mutex(inst.mutex);
inst.errors.clear();
inst.lastError = nullptr;
}

View File

@@ -0,0 +1,78 @@
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include "frc/Errors.h"
#include <exception>
#include <hal/DriverStation.h>
#include <hal/HALBase.h>
#include <wpi/Path.h>
#include <wpi/SmallString.h>
#include <wpi/StackTrace.h>
using namespace frc;
RuntimeError::RuntimeError(int32_t code, const wpi::Twine& message,
const wpi::Twine& loc, wpi::StringRef stack)
: runtime_error{message.str()}, m_data{std::make_shared<Data>()} {
m_data->code = code;
m_data->loc = loc.str();
m_data->stack = stack;
}
RuntimeError::RuntimeError(int32_t code, const wpi::Twine& message,
const char* fileName, int lineNumber,
const char* funcName, wpi::StringRef stack)
: RuntimeError{code, message,
funcName + wpi::Twine{" ["} +
wpi::sys::path::filename(fileName) + ":" +
wpi::Twine{lineNumber} + "]",
stack} {}
void RuntimeError::Report() const {
HAL_SendError(m_data->code < 0, m_data->code, 0, what(), m_data->loc.c_str(),
m_data->stack.c_str(), 1);
}
const char* frc::GetErrorMessage(int32_t* code) {
using namespace err;
using namespace warn;
switch (*code) {
#define S(label, offset, message) \
case label: \
return message;
#include "frc/WPIErrors.mac"
#include "frc/WPIWarnings.mac"
#undef S
default:
return HAL_GetLastError(code);
}
}
void frc::ReportError(int32_t status, const wpi::Twine& message,
const char* fileName, int lineNumber,
const char* funcName) {
if (status == 0) {
return;
}
const char* statusMessage = GetErrorMessage(&status);
auto stack = wpi::GetStackTrace(2);
wpi::SmallString<128> buf;
HAL_SendError(status < 0, status, 0,
(statusMessage + wpi::Twine{": "} + message)
.toNullTerminatedStringRef(buf)
.data(),
funcName, stack.c_str(), 1);
}
RuntimeError frc::MakeError(int32_t status, const wpi::Twine& message,
const char* fileName, int lineNumber,
const char* funcName) {
const char* statusMessage = GetErrorMessage(&status);
auto stack = wpi::GetStackTrace(2);
return RuntimeError{status, statusMessage + wpi::Twine{": "} + message,
fileName, lineNumber,
funcName, stack};
}

View File

@@ -1,43 +0,0 @@
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include "frc/GearTooth.h"
#include "frc/smartdashboard/SendableBuilder.h"
#include "frc/smartdashboard/SendableRegistry.h"
using namespace frc;
constexpr double GearTooth::kGearToothThreshold;
GearTooth::GearTooth(int channel, bool directionSensitive) : Counter(channel) {
EnableDirectionSensing(directionSensitive);
SendableRegistry::GetInstance().SetName(this, "GearTooth", channel);
}
GearTooth::GearTooth(DigitalSource* source, bool directionSensitive)
: Counter(source) {
EnableDirectionSensing(directionSensitive);
SendableRegistry::GetInstance().SetName(this, "GearTooth",
source->GetChannel());
}
GearTooth::GearTooth(std::shared_ptr<DigitalSource> source,
bool directionSensitive)
: Counter(source) {
EnableDirectionSensing(directionSensitive);
SendableRegistry::GetInstance().SetName(this, "GearTooth",
source->GetChannel());
}
void GearTooth::EnableDirectionSensing(bool directionSensitive) {
if (directionSensitive) {
SetPulseLengthMode(kGearToothThreshold);
}
}
void GearTooth::InitSendable(SendableBuilder& builder) {
Counter::InitSendable(builder);
builder.SetSmartDashboardType("Gear Tooth");
}

View File

@@ -7,13 +7,14 @@
#include <hal/DriverStation.h>
#include "frc/DriverStation.h"
#include "frc/WPIErrors.h"
#include "frc/Errors.h"
using namespace frc;
GenericHID::GenericHID(int port) : m_ds(&DriverStation::GetInstance()) {
if (port >= DriverStation::kJoystickPorts) {
wpi_setWPIError(BadJoystickIndex);
if (port < 0 || port >= DriverStation::kJoystickPorts) {
throw FRC_MakeError(warn::BadJoystickIndex,
"port " + wpi::Twine{port} + "out of range");
}
m_port = port;
}

View File

@@ -1,27 +0,0 @@
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include "frc/GyroBase.h"
#include "frc/WPIErrors.h"
#include "frc/smartdashboard/SendableBuilder.h"
using namespace frc;
double GyroBase::PIDGet() {
switch (GetPIDSourceType()) {
case PIDSourceType::kRate:
return GetRate();
case PIDSourceType::kDisplacement:
return GetAngle();
default:
return 0;
}
}
void GyroBase::InitSendable(SendableBuilder& builder) {
builder.SetSmartDashboardType("Gyro");
builder.AddDoubleProperty(
"Value", [=]() { return GetAngle(); }, nullptr);
}

View File

@@ -9,7 +9,7 @@
#include <hal/FRCUsageReporting.h>
#include <hal/I2C.h>
#include "frc/WPIErrors.h"
#include "frc/Errors.h"
using namespace frc;
@@ -17,7 +17,7 @@ I2C::I2C(Port port, int deviceAddress)
: m_port(static_cast<HAL_I2CPort>(port)), m_deviceAddress(deviceAddress) {
int32_t status = 0;
HAL_InitializeI2C(m_port, &status);
// wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Port " + wpi::Twine{static_cast<int>(port)});
HAL_Report(HALUsageReporting::kResourceType_I2C, deviceAddress);
}
@@ -31,7 +31,6 @@ bool I2C::Transaction(uint8_t* dataToSend, int sendSize, uint8_t* dataReceived,
int32_t status = 0;
status = HAL_TransactionI2C(m_port, m_deviceAddress, dataToSend, sendSize,
dataReceived, receiveSize);
// wpi_setHALError(status);
return status < 0;
}
@@ -56,12 +55,10 @@ bool I2C::WriteBulk(uint8_t* data, int count) {
bool I2C::Read(int registerAddress, int count, uint8_t* buffer) {
if (count < 1) {
wpi_setWPIErrorWithContext(ParameterOutOfRange, "count");
return true;
throw FRC_MakeError(err::ParameterOutOfRange, "count " + wpi::Twine{count});
}
if (buffer == nullptr) {
wpi_setWPIErrorWithContext(NullParameter, "buffer");
return true;
if (!buffer) {
throw FRC_MakeError(err::NullParameter, "buffer");
}
uint8_t regAddr = registerAddress;
return Transaction(&regAddr, sizeof(regAddr), buffer, count);
@@ -69,12 +66,10 @@ bool I2C::Read(int registerAddress, int count, uint8_t* buffer) {
bool I2C::ReadOnly(int count, uint8_t* buffer) {
if (count < 1) {
wpi_setWPIErrorWithContext(ParameterOutOfRange, "count");
return true;
throw FRC_MakeError(err::ParameterOutOfRange, "count " + wpi::Twine{count});
}
if (buffer == nullptr) {
wpi_setWPIErrorWithContext(NullParameter, "buffer");
return true;
if (!buffer) {
throw FRC_MakeError(err::NullParameter, "buffer");
}
return HAL_ReadI2C(m_port, m_deviceAddress, buffer, count) < 0;
}

View File

@@ -4,8 +4,8 @@
#include "frc/InterruptableSensorBase.h"
#include "frc/Errors.h"
#include "frc/Utility.h"
#include "frc/WPIErrors.h"
using namespace frc;
@@ -20,15 +20,8 @@ InterruptableSensorBase::~InterruptableSensorBase() {
void InterruptableSensorBase::RequestInterrupts(
HAL_InterruptHandlerFunction handler, void* param) {
if (StatusIsFatal()) {
return;
}
wpi_assert(m_interrupt == HAL_kInvalidHandle);
FRC_Assert(m_interrupt == HAL_kInvalidHandle);
AllocateInterrupts(false);
if (StatusIsFatal()) {
return; // if allocate failed, out of interrupts
}
int32_t status = 0;
HAL_RequestInterrupts(
@@ -37,19 +30,12 @@ void InterruptableSensorBase::RequestInterrupts(
&status);
SetUpSourceEdge(true, false);
HAL_AttachInterruptHandler(m_interrupt, handler, param, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "AttachInterruptHandler");
}
void InterruptableSensorBase::RequestInterrupts(InterruptEventHandler handler) {
if (StatusIsFatal()) {
return;
}
wpi_assert(m_interrupt == HAL_kInvalidHandle);
FRC_Assert(m_interrupt == HAL_kInvalidHandle);
AllocateInterrupts(false);
if (StatusIsFatal()) {
return; // if allocate failed, out of interrupts
}
m_interruptHandler =
std::make_unique<InterruptEventHandler>(std::move(handler));
@@ -74,34 +60,24 @@ void InterruptableSensorBase::RequestInterrupts(InterruptEventHandler handler) {
(*self)(res);
},
m_interruptHandler.get(), &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "AttachInterruptHandler");
}
void InterruptableSensorBase::RequestInterrupts() {
if (StatusIsFatal()) {
return;
}
wpi_assert(m_interrupt == HAL_kInvalidHandle);
FRC_Assert(m_interrupt == HAL_kInvalidHandle);
AllocateInterrupts(true);
if (StatusIsFatal()) {
return; // if allocate failed, out of interrupts
}
int32_t status = 0;
HAL_RequestInterrupts(
m_interrupt, GetPortHandleForRouting(),
static_cast<HAL_AnalogTriggerType>(GetAnalogTriggerTypeForRouting()),
&status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "RequestInterrupts");
SetUpSourceEdge(true, false);
}
void InterruptableSensorBase::CancelInterrupts() {
if (StatusIsFatal()) {
return;
}
wpi_assert(m_interrupt != HAL_kInvalidHandle);
FRC_Assert(m_interrupt != HAL_kInvalidHandle);
int32_t status = 0;
HAL_CleanInterrupts(m_interrupt, &status);
// Ignore status, as an invalid handle just needs to be ignored.
@@ -111,15 +87,12 @@ void InterruptableSensorBase::CancelInterrupts() {
InterruptableSensorBase::WaitResult InterruptableSensorBase::WaitForInterrupt(
double timeout, bool ignorePrevious) {
if (StatusIsFatal()) {
return InterruptableSensorBase::kTimeout;
}
wpi_assert(m_interrupt != HAL_kInvalidHandle);
FRC_Assert(m_interrupt != HAL_kInvalidHandle);
int32_t status = 0;
int result;
result = HAL_WaitForInterrupt(m_interrupt, timeout, ignorePrevious, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "WaitForInterrupt");
// Rising edge result is the interrupt bit set in the byte 0xFF
// Falling edge result is the interrupt bit set in the byte 0xFF00
@@ -131,69 +104,53 @@ InterruptableSensorBase::WaitResult InterruptableSensorBase::WaitForInterrupt(
}
void InterruptableSensorBase::EnableInterrupts() {
if (StatusIsFatal()) {
return;
}
wpi_assert(m_interrupt != HAL_kInvalidHandle);
FRC_Assert(m_interrupt != HAL_kInvalidHandle);
int32_t status = 0;
HAL_EnableInterrupts(m_interrupt, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "EnableInterrupts");
}
void InterruptableSensorBase::DisableInterrupts() {
if (StatusIsFatal()) {
return;
}
wpi_assert(m_interrupt != HAL_kInvalidHandle);
FRC_Assert(m_interrupt != HAL_kInvalidHandle);
int32_t status = 0;
HAL_DisableInterrupts(m_interrupt, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "DisableInterrupts");
}
double InterruptableSensorBase::ReadRisingTimestamp() {
if (StatusIsFatal()) {
return 0.0;
}
wpi_assert(m_interrupt != HAL_kInvalidHandle);
FRC_Assert(m_interrupt != HAL_kInvalidHandle);
int32_t status = 0;
int64_t timestamp = HAL_ReadInterruptRisingTimestamp(m_interrupt, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "ReadRisingTimestamp");
return timestamp * 1e-6;
}
double InterruptableSensorBase::ReadFallingTimestamp() {
if (StatusIsFatal()) {
return 0.0;
}
wpi_assert(m_interrupt != HAL_kInvalidHandle);
FRC_Assert(m_interrupt != HAL_kInvalidHandle);
int32_t status = 0;
int64_t timestamp = HAL_ReadInterruptFallingTimestamp(m_interrupt, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "ReadFallingTimestamp");
return timestamp * 1e-6;
}
void InterruptableSensorBase::SetUpSourceEdge(bool risingEdge,
bool fallingEdge) {
if (StatusIsFatal()) {
return;
}
if (m_interrupt == HAL_kInvalidHandle) {
wpi_setWPIErrorWithContext(
NullParameter,
throw FRC_MakeError(
err::NullParameter,
"You must call RequestInterrupts before SetUpSourceEdge");
return;
}
if (m_interrupt != HAL_kInvalidHandle) {
int32_t status = 0;
HAL_SetInterruptUpSourceEdge(m_interrupt, risingEdge, fallingEdge, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "SetUpSourceEdge");
}
}
void InterruptableSensorBase::AllocateInterrupts(bool watcher) {
wpi_assert(m_interrupt == HAL_kInvalidHandle);
FRC_Assert(m_interrupt == HAL_kInvalidHandle);
// Expects the calling leaf class to allocate an interrupt index.
int32_t status = 0;
m_interrupt = HAL_InitializeInterrupts(watcher, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "AllocateInterrupts");
}

View File

@@ -1,46 +0,0 @@
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include "frc/IterativeRobot.h"
#include <hal/DriverStation.h>
#include <hal/FRCUsageReporting.h>
#include "frc/DriverStation.h"
using namespace frc;
static constexpr auto kPacketPeriod = 0.02_s;
IterativeRobot::IterativeRobot() : IterativeRobotBase(kPacketPeriod) {
HAL_Report(HALUsageReporting::kResourceType_Framework,
HALUsageReporting::kFramework_Iterative);
}
void IterativeRobot::StartCompetition() {
RobotInit();
if constexpr (IsSimulation()) {
SimulationInit();
}
// Tell the DS that the robot is ready to be enabled
HAL_ObserveUserProgramStarting();
// Loop forever, calling the appropriate mode-dependent function
while (true) {
// Wait for driver station data so the loop doesn't hog the CPU
DriverStation::GetInstance().WaitForData();
if (m_exit) {
break;
}
LoopFunc();
}
}
void IterativeRobot::EndCompetition() {
m_exit = true;
DriverStation::GetInstance().WakeupWaitForData();
}

View File

@@ -100,6 +100,10 @@ void IterativeRobotBase::SetNetworkTablesFlushEnabled(bool enabled) {
m_ntFlushEnabled = enabled;
}
units::second_t IterativeRobotBase::GetPeriod() const {
return m_period;
}
void IterativeRobotBase::LoopFunc() {
m_watchdog.Reset();
@@ -108,7 +112,7 @@ void IterativeRobotBase::LoopFunc() {
// Call DisabledInit() if we are now just entering disabled mode from
// either a different mode or from power-on.
if (m_lastMode != Mode::kDisabled) {
LiveWindow::GetInstance()->SetEnabled(false);
LiveWindow::GetInstance().SetEnabled(false);
Shuffleboard::DisableActuatorWidgets();
DisabledInit();
m_watchdog.AddEpoch("DisabledInit()");
@@ -122,7 +126,7 @@ void IterativeRobotBase::LoopFunc() {
// Call AutonomousInit() if we are now just entering autonomous mode from
// either a different mode or from power-on.
if (m_lastMode != Mode::kAutonomous) {
LiveWindow::GetInstance()->SetEnabled(false);
LiveWindow::GetInstance().SetEnabled(false);
Shuffleboard::DisableActuatorWidgets();
AutonomousInit();
m_watchdog.AddEpoch("AutonomousInit()");
@@ -136,7 +140,7 @@ void IterativeRobotBase::LoopFunc() {
// Call TeleopInit() if we are now just entering teleop mode from
// either a different mode or from power-on.
if (m_lastMode != Mode::kTeleop) {
LiveWindow::GetInstance()->SetEnabled(false);
LiveWindow::GetInstance().SetEnabled(false);
Shuffleboard::DisableActuatorWidgets();
TeleopInit();
m_watchdog.AddEpoch("TeleopInit()");
@@ -150,7 +154,7 @@ void IterativeRobotBase::LoopFunc() {
// Call TestInit() if we are now just entering test mode from
// either a different mode or from power-on.
if (m_lastMode != Mode::kTest) {
LiveWindow::GetInstance()->SetEnabled(true);
LiveWindow::GetInstance().SetEnabled(true);
Shuffleboard::EnableActuatorWidgets();
TestInit();
m_watchdog.AddEpoch("TestInit()");
@@ -167,7 +171,7 @@ void IterativeRobotBase::LoopFunc() {
SmartDashboard::UpdateValues();
m_watchdog.AddEpoch("SmartDashboard::UpdateValues()");
LiveWindow::GetInstance()->UpdateValues();
LiveWindow::GetInstance().UpdateValues();
m_watchdog.AddEpoch("LiveWindow::UpdateValues()");
Shuffleboard::Update();
m_watchdog.AddEpoch("Shuffleboard::Update()");

View File

@@ -12,7 +12,7 @@
#include <wpi/raw_ostream.h>
#include "frc/DriverStation.h"
#include "frc/WPIErrors.h"
#include "frc/Errors.h"
using namespace frc;
@@ -30,16 +30,13 @@ MotorSafety::~MotorSafety() {
}
MotorSafety::MotorSafety(MotorSafety&& rhs)
: ErrorBase(std::move(rhs)),
m_expiration(std::move(rhs.m_expiration)),
: m_expiration(std::move(rhs.m_expiration)),
m_enabled(std::move(rhs.m_enabled)),
m_stopTime(std::move(rhs.m_stopTime)) {}
MotorSafety& MotorSafety::operator=(MotorSafety&& rhs) {
std::scoped_lock lock(m_thisMutex, rhs.m_thisMutex);
ErrorBase::operator=(std::move(rhs));
m_expiration = std::move(rhs.m_expiration);
m_enabled = std::move(rhs.m_enabled);
m_stopTime = std::move(rhs.m_stopTime);
@@ -97,7 +94,7 @@ void MotorSafety::Check() {
wpi::raw_svector_ostream desc(buf);
GetDescription(desc);
desc << "... Output not updated often enough.";
wpi_setWPIErrorWithContext(Timeout, desc.str());
FRC_ReportError(err::Timeout, desc.str());
StopMotor();
}
}

View File

@@ -11,20 +11,20 @@
#include <hal/Threads.h>
#include <wpi/SmallString.h>
#include "frc/Errors.h"
#include "frc/Timer.h"
#include "frc/Utility.h"
#include "frc/WPIErrors.h"
using namespace frc;
Notifier::Notifier(std::function<void()> handler) {
if (handler == nullptr) {
wpi_setWPIErrorWithContext(NullParameter, "handler must not be nullptr");
if (!handler) {
throw FRC_MakeError(err::NullParameter, "handler");
}
m_handler = handler;
int32_t status = 0;
m_notifier = HAL_InitializeNotifier(&status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "InitializeNotifier");
m_thread = std::thread([=] {
for (;;) {
@@ -60,13 +60,13 @@ Notifier::Notifier(std::function<void()> handler) {
}
Notifier::Notifier(int priority, std::function<void()> handler) {
if (handler == nullptr) {
wpi_setWPIErrorWithContext(NullParameter, "handler must not be nullptr");
if (!handler) {
throw FRC_MakeError(err::NullParameter, "handler");
}
m_handler = handler;
int32_t status = 0;
m_notifier = HAL_InitializeNotifier(&status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "InitializeNotifier");
m_thread = std::thread([=] {
int32_t status = 0;
@@ -107,7 +107,7 @@ Notifier::~Notifier() {
// atomically set handle to 0, then clean
HAL_NotifierHandle handle = m_notifier.exchange(0);
HAL_StopNotifier(handle, &status);
wpi_setHALError(status);
FRC_ReportError(status, "StopNotifier");
// Join the thread to ensure the handler has exited.
if (m_thread.joinable()) {
@@ -118,8 +118,7 @@ Notifier::~Notifier() {
}
Notifier::Notifier(Notifier&& rhs)
: ErrorBase(std::move(rhs)),
m_thread(std::move(rhs.m_thread)),
: m_thread(std::move(rhs.m_thread)),
m_notifier(rhs.m_notifier.load()),
m_handler(std::move(rhs.m_handler)),
m_expirationTime(std::move(rhs.m_expirationTime)),
@@ -129,8 +128,6 @@ Notifier::Notifier(Notifier&& rhs)
}
Notifier& Notifier::operator=(Notifier&& rhs) {
ErrorBase::operator=(std::move(rhs));
m_thread = std::move(rhs.m_thread);
m_notifier = rhs.m_notifier.load();
rhs.m_notifier = HAL_kInvalidHandle;
@@ -183,7 +180,7 @@ void Notifier::Stop() {
m_periodic = false;
int32_t status = 0;
HAL_CancelNotifierAlarm(m_notifier, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "CancelNotifierAlarm");
}
void Notifier::UpdateAlarm(uint64_t triggerTime) {
@@ -194,7 +191,7 @@ void Notifier::UpdateAlarm(uint64_t triggerTime) {
return;
}
HAL_UpdateNotifierAlarm(notifier, triggerTime, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "UpdateNotifierAlarm");
}
void Notifier::UpdateAlarm() {

View File

@@ -1,358 +0,0 @@
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include "frc/PIDBase.h"
#include <algorithm>
#include <cmath>
#include <hal/FRCUsageReporting.h>
#include "frc/PIDOutput.h"
#include "frc/smartdashboard/SendableBuilder.h"
#include "frc/smartdashboard/SendableRegistry.h"
using namespace frc;
template <class T>
constexpr const T& clamp(const T& value, const T& low, const T& high) {
return std::max(low, std::min(value, high));
}
PIDBase::PIDBase(double Kp, double Ki, double Kd, PIDSource& source,
PIDOutput& output)
: PIDBase(Kp, Ki, Kd, 0.0, source, output) {}
PIDBase::PIDBase(double Kp, double Ki, double Kd, double Kf, PIDSource& source,
PIDOutput& output) {
m_P = Kp;
m_I = Ki;
m_D = Kd;
m_F = Kf;
m_pidInput = &source;
m_filter = LinearFilter<double>::MovingAverage(1);
m_pidOutput = &output;
m_setpointTimer.Start();
static int instances = 0;
instances++;
HAL_Report(HALUsageReporting::kResourceType_PIDController, instances);
SendableRegistry::GetInstance().Add(this, "PIDController", instances);
}
double PIDBase::Get() const {
std::scoped_lock lock(m_thisMutex);
return m_result;
}
void PIDBase::SetContinuous(bool continuous) {
std::scoped_lock lock(m_thisMutex);
m_continuous = continuous;
}
void PIDBase::SetInputRange(double minimumInput, double maximumInput) {
{
std::scoped_lock lock(m_thisMutex);
m_minimumInput = minimumInput;
m_maximumInput = maximumInput;
m_inputRange = maximumInput - minimumInput;
}
SetSetpoint(m_setpoint);
}
void PIDBase::SetOutputRange(double minimumOutput, double maximumOutput) {
std::scoped_lock lock(m_thisMutex);
m_minimumOutput = minimumOutput;
m_maximumOutput = maximumOutput;
}
void PIDBase::SetPID(double p, double i, double d) {
{
std::scoped_lock lock(m_thisMutex);
m_P = p;
m_I = i;
m_D = d;
}
}
void PIDBase::SetPID(double p, double i, double d, double f) {
std::scoped_lock lock(m_thisMutex);
m_P = p;
m_I = i;
m_D = d;
m_F = f;
}
void PIDBase::SetP(double p) {
std::scoped_lock lock(m_thisMutex);
m_P = p;
}
void PIDBase::SetI(double i) {
std::scoped_lock lock(m_thisMutex);
m_I = i;
}
void PIDBase::SetD(double d) {
std::scoped_lock lock(m_thisMutex);
m_D = d;
}
void PIDBase::SetF(double f) {
std::scoped_lock lock(m_thisMutex);
m_F = f;
}
double PIDBase::GetP() const {
std::scoped_lock lock(m_thisMutex);
return m_P;
}
double PIDBase::GetI() const {
std::scoped_lock lock(m_thisMutex);
return m_I;
}
double PIDBase::GetD() const {
std::scoped_lock lock(m_thisMutex);
return m_D;
}
double PIDBase::GetF() const {
std::scoped_lock lock(m_thisMutex);
return m_F;
}
void PIDBase::SetSetpoint(double setpoint) {
{
std::scoped_lock lock(m_thisMutex);
if (m_maximumInput > m_minimumInput) {
if (setpoint > m_maximumInput) {
m_setpoint = m_maximumInput;
} else if (setpoint < m_minimumInput) {
m_setpoint = m_minimumInput;
} else {
m_setpoint = setpoint;
}
} else {
m_setpoint = setpoint;
}
}
}
double PIDBase::GetSetpoint() const {
std::scoped_lock lock(m_thisMutex);
return m_setpoint;
}
double PIDBase::GetDeltaSetpoint() const {
std::scoped_lock lock(m_thisMutex);
return (m_setpoint - m_prevSetpoint) / m_setpointTimer.Get();
}
double PIDBase::GetError() const {
double setpoint = GetSetpoint();
{
std::scoped_lock lock(m_thisMutex);
return GetContinuousError(setpoint - m_pidInput->PIDGet());
}
}
double PIDBase::GetAvgError() const {
return GetError();
}
void PIDBase::SetPIDSourceType(PIDSourceType pidSource) {
m_pidInput->SetPIDSourceType(pidSource);
}
PIDSourceType PIDBase::GetPIDSourceType() const {
return m_pidInput->GetPIDSourceType();
}
void PIDBase::SetTolerance(double percent) {
std::scoped_lock lock(m_thisMutex);
m_toleranceType = kPercentTolerance;
m_tolerance = percent;
}
void PIDBase::SetAbsoluteTolerance(double absTolerance) {
std::scoped_lock lock(m_thisMutex);
m_toleranceType = kAbsoluteTolerance;
m_tolerance = absTolerance;
}
void PIDBase::SetPercentTolerance(double percent) {
std::scoped_lock lock(m_thisMutex);
m_toleranceType = kPercentTolerance;
m_tolerance = percent;
}
void PIDBase::SetToleranceBuffer(int bufLength) {
std::scoped_lock lock(m_thisMutex);
m_filter = LinearFilter<double>::MovingAverage(bufLength);
}
bool PIDBase::OnTarget() const {
double error = GetError();
std::scoped_lock lock(m_thisMutex);
switch (m_toleranceType) {
case kPercentTolerance:
return std::fabs(error) < m_tolerance / 100 * m_inputRange;
break;
case kAbsoluteTolerance:
return std::fabs(error) < m_tolerance;
break;
case kNoTolerance:
// TODO: this case needs an error
return false;
}
return false;
}
void PIDBase::Reset() {
std::scoped_lock lock(m_thisMutex);
m_prevError = 0;
m_totalError = 0;
m_result = 0;
}
void PIDBase::PIDWrite(double output) {
SetSetpoint(output);
}
void PIDBase::InitSendable(SendableBuilder& builder) {
builder.SetSmartDashboardType("PIDController");
builder.SetSafeState([=]() { Reset(); });
builder.AddDoubleProperty(
"p", [=]() { return GetP(); }, [=](double value) { SetP(value); });
builder.AddDoubleProperty(
"i", [=]() { return GetI(); }, [=](double value) { SetI(value); });
builder.AddDoubleProperty(
"d", [=]() { return GetD(); }, [=](double value) { SetD(value); });
builder.AddDoubleProperty(
"f", [=]() { return GetF(); }, [=](double value) { SetF(value); });
builder.AddDoubleProperty(
"setpoint", [=]() { return GetSetpoint(); },
[=](double value) { SetSetpoint(value); });
}
void PIDBase::Calculate() {
if (m_pidInput == nullptr || m_pidOutput == nullptr) {
return;
}
bool enabled;
{
std::scoped_lock lock(m_thisMutex);
enabled = m_enabled;
}
if (enabled) {
double input;
// Storage for function inputs
PIDSourceType pidSourceType;
double P;
double I;
double D;
double feedForward = CalculateFeedForward();
double minimumOutput;
double maximumOutput;
// Storage for function input-outputs
double prevError;
double error;
double totalError;
{
std::scoped_lock lock(m_thisMutex);
input = m_filter.Calculate(m_pidInput->PIDGet());
pidSourceType = m_pidInput->GetPIDSourceType();
P = m_P;
I = m_I;
D = m_D;
minimumOutput = m_minimumOutput;
maximumOutput = m_maximumOutput;
prevError = m_prevError;
error = GetContinuousError(m_setpoint - input);
totalError = m_totalError;
}
// Storage for function outputs
double result;
if (pidSourceType == PIDSourceType::kRate) {
if (P != 0) {
totalError =
clamp(totalError + error, minimumOutput / P, maximumOutput / P);
}
result = D * error + P * totalError + feedForward;
} else {
if (I != 0) {
totalError =
clamp(totalError + error, minimumOutput / I, maximumOutput / I);
}
result =
P * error + I * totalError + D * (error - prevError) + feedForward;
}
result = clamp(result, minimumOutput, maximumOutput);
{
// Ensures m_enabled check and PIDWrite() call occur atomically
std::scoped_lock pidWriteLock(m_pidWriteMutex);
std::unique_lock mainLock(m_thisMutex);
if (m_enabled) {
// Don't block other PIDBase operations on PIDWrite()
mainLock.unlock();
m_pidOutput->PIDWrite(result);
}
}
std::scoped_lock lock(m_thisMutex);
m_prevError = m_error;
m_error = error;
m_totalError = totalError;
m_result = result;
}
}
double PIDBase::CalculateFeedForward() {
if (m_pidInput->GetPIDSourceType() == PIDSourceType::kRate) {
return m_F * GetSetpoint();
} else {
double temp = m_F * GetDeltaSetpoint();
m_prevSetpoint = m_setpoint;
m_setpointTimer.Reset();
return temp;
}
}
double PIDBase::GetContinuousError(double error) const {
if (m_continuous && m_inputRange != 0) {
error = std::fmod(error, m_inputRange);
if (std::fabs(error) > m_inputRange / 2) {
if (error > 0) {
return error - m_inputRange;
} else {
return error + m_inputRange;
}
}
}
return error;
}

View File

@@ -1,83 +0,0 @@
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include "frc/PIDController.h"
#include "frc/Notifier.h"
#include "frc/PIDOutput.h"
#include "frc/smartdashboard/SendableBuilder.h"
using namespace frc;
PIDController::PIDController(double Kp, double Ki, double Kd, PIDSource* source,
PIDOutput* output, double period)
: PIDController(Kp, Ki, Kd, 0.0, *source, *output, period) {}
PIDController::PIDController(double Kp, double Ki, double Kd, double Kf,
PIDSource* source, PIDOutput* output,
double period)
: PIDController(Kp, Ki, Kd, Kf, *source, *output, period) {}
PIDController::PIDController(double Kp, double Ki, double Kd, PIDSource& source,
PIDOutput& output, double period)
: PIDController(Kp, Ki, Kd, 0.0, source, output, period) {}
PIDController::PIDController(double Kp, double Ki, double Kd, double Kf,
PIDSource& source, PIDOutput& output,
double period)
: PIDBase(Kp, Ki, Kd, Kf, source, output) {
m_controlLoop = std::make_unique<Notifier>(&PIDController::Calculate, this);
m_controlLoop->StartPeriodic(units::second_t(period));
}
PIDController::~PIDController() {
// Forcefully stopping the notifier so the callback can successfully run.
m_controlLoop->Stop();
}
void PIDController::Enable() {
{
std::scoped_lock lock(m_thisMutex);
m_enabled = true;
}
}
void PIDController::Disable() {
{
// Ensures m_enabled modification and PIDWrite() call occur atomically
std::scoped_lock pidWriteLock(m_pidWriteMutex);
{
std::scoped_lock mainLock(m_thisMutex);
m_enabled = false;
}
m_pidOutput->PIDWrite(0);
}
}
void PIDController::SetEnabled(bool enable) {
if (enable) {
Enable();
} else {
Disable();
}
}
bool PIDController::IsEnabled() const {
std::scoped_lock lock(m_thisMutex);
return m_enabled;
}
void PIDController::Reset() {
Disable();
PIDBase::Reset();
}
void PIDController::InitSendable(SendableBuilder& builder) {
PIDBase::InitSendable(builder);
builder.AddBooleanProperty(
"enabled", [=]() { return IsEnabled(); },
[=](bool value) { SetEnabled(value); });
}

View File

@@ -1,15 +0,0 @@
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include "frc/PIDSource.h"
using namespace frc;
void PIDSource::SetPIDSourceType(PIDSourceType pidSource) {
m_pidSource = pidSource;
}
PIDSourceType PIDSource::GetPIDSourceType() const {
return m_pidSource;
}

View File

@@ -10,141 +10,100 @@
#include <hal/HALBase.h>
#include <hal/PWM.h>
#include <hal/Ports.h>
#include <wpi/StackTrace.h>
#include "frc/Errors.h"
#include "frc/SensorUtil.h"
#include "frc/Utility.h"
#include "frc/WPIErrors.h"
#include "frc/smartdashboard/SendableBuilder.h"
#include "frc/smartdashboard/SendableRegistry.h"
using namespace frc;
PWM::PWM(int channel) {
PWM::PWM(int channel, bool registerSendable) {
if (!SensorUtil::CheckPWMChannel(channel)) {
wpi_setWPIErrorWithContext(ChannelIndexOutOfRange,
"PWM Channel " + wpi::Twine(channel));
throw FRC_MakeError(err::ChannelIndexOutOfRange,
"PWM Channel " + wpi::Twine{channel});
return;
}
auto stack = wpi::GetStackTrace(1);
int32_t status = 0;
m_handle = HAL_InitializePWMPort(HAL_GetPort(channel), &status);
if (status != 0) {
wpi_setHALErrorWithRange(status, 0, HAL_GetNumPWMChannels(), channel);
m_channel = std::numeric_limits<int>::max();
m_handle = HAL_kInvalidHandle;
return;
}
m_handle =
HAL_InitializePWMPort(HAL_GetPort(channel), stack.c_str(), &status);
FRC_CheckErrorStatus(status, "PWM Channel " + wpi::Twine{channel});
m_channel = channel;
HAL_SetPWMDisabled(m_handle, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "SetPWMDisabled");
status = 0;
HAL_SetPWMEliminateDeadband(m_handle, false, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "SetPWMEliminateDeadband");
HAL_Report(HALUsageReporting::kResourceType_PWM, channel + 1);
SendableRegistry::GetInstance().AddLW(this, "PWM", channel);
SetSafetyEnabled(false);
if (registerSendable) {
SendableRegistry::GetInstance().AddLW(this, "PWM", channel);
}
}
PWM::~PWM() {
int32_t status = 0;
HAL_SetPWMDisabled(m_handle, &status);
wpi_setHALError(status);
FRC_ReportError(status, "SetPWMDisabled");
HAL_FreePWMPort(m_handle, &status);
wpi_setHALError(status);
}
void PWM::StopMotor() {
SetDisabled();
}
void PWM::GetDescription(wpi::raw_ostream& desc) const {
desc << "PWM " << GetChannel();
FRC_ReportError(status, "FreePWM");
}
void PWM::SetRaw(uint16_t value) {
if (StatusIsFatal()) {
return;
}
int32_t status = 0;
HAL_SetPWMRaw(m_handle, value, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "SetRaw");
}
uint16_t PWM::GetRaw() const {
if (StatusIsFatal()) {
return 0;
}
int32_t status = 0;
uint16_t value = HAL_GetPWMRaw(m_handle, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "GetRaw");
return value;
}
void PWM::SetPosition(double pos) {
if (StatusIsFatal()) {
return;
}
int32_t status = 0;
HAL_SetPWMPosition(m_handle, pos, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "SetPosition");
}
double PWM::GetPosition() const {
if (StatusIsFatal()) {
return 0.0;
}
int32_t status = 0;
double position = HAL_GetPWMPosition(m_handle, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "GetPosition");
return position;
}
void PWM::SetSpeed(double speed) {
if (StatusIsFatal()) {
return;
}
int32_t status = 0;
HAL_SetPWMSpeed(m_handle, speed, &status);
wpi_setHALError(status);
Feed();
FRC_CheckErrorStatus(status, "SetSpeed");
}
double PWM::GetSpeed() const {
if (StatusIsFatal()) {
return 0.0;
}
int32_t status = 0;
double speed = HAL_GetPWMSpeed(m_handle, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "GetSpeed");
return speed;
}
void PWM::SetDisabled() {
if (StatusIsFatal()) {
return;
}
int32_t status = 0;
HAL_SetPWMDisabled(m_handle, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "SetDisabled");
}
void PWM::SetPeriodMultiplier(PeriodMultiplier mult) {
if (StatusIsFatal()) {
return;
}
int32_t status = 0;
switch (mult) {
@@ -163,49 +122,35 @@ void PWM::SetPeriodMultiplier(PeriodMultiplier mult) {
wpi_assert(false);
}
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "SetPeriodMultiplier");
}
void PWM::SetZeroLatch() {
if (StatusIsFatal()) {
return;
}
int32_t status = 0;
HAL_LatchPWMZero(m_handle, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "SetZeroLatch");
}
void PWM::EnableDeadbandElimination(bool eliminateDeadband) {
if (StatusIsFatal()) {
return;
}
int32_t status = 0;
HAL_SetPWMEliminateDeadband(m_handle, eliminateDeadband, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "EnableDeadbandElimination");
}
void PWM::SetBounds(double max, double deadbandMax, double center,
double deadbandMin, double min) {
if (StatusIsFatal()) {
return;
}
int32_t status = 0;
HAL_SetPWMConfig(m_handle, max, deadbandMax, center, deadbandMin, min,
&status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "SetBounds");
}
void PWM::SetRawBounds(int max, int deadbandMax, int center, int deadbandMin,
int min) {
if (StatusIsFatal()) {
return;
}
int32_t status = 0;
HAL_SetPWMConfigRaw(m_handle, max, deadbandMax, center, deadbandMin, min,
&status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "SetRawBounds");
}
void PWM::GetRawBounds(int* max, int* deadbandMax, int* center,
@@ -213,7 +158,7 @@ void PWM::GetRawBounds(int* max, int* deadbandMax, int* center,
int32_t status = 0;
HAL_GetPWMConfigRaw(m_handle, max, deadbandMax, center, deadbandMin, min,
&status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "GetRawBounds");
}
int PWM::GetChannel() const {
@@ -223,8 +168,7 @@ int PWM::GetChannel() const {
void PWM::InitSendable(SendableBuilder& builder) {
builder.SetSmartDashboardType("PWM");
builder.SetActuator(true);
builder.SetSafeState([=]() { SetDisabled(); });
builder.SetSafeState([=] { SetDisabled(); });
builder.AddDoubleProperty(
"Value", [=]() { return GetRaw(); },
[=](double value) { SetRaw(value); });
"Value", [=] { return GetRaw(); }, [=](double value) { SetRaw(value); });
}

View File

@@ -1,48 +0,0 @@
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include "frc/PWMSpeedController.h"
#include "frc/smartdashboard/SendableBuilder.h"
using namespace frc;
void PWMSpeedController::Set(double speed) {
SetSpeed(m_isInverted ? -speed : speed);
}
double PWMSpeedController::Get() const {
return GetSpeed() * (m_isInverted ? -1.0 : 1.0);
}
void PWMSpeedController::SetInverted(bool isInverted) {
m_isInverted = isInverted;
}
bool PWMSpeedController::GetInverted() const {
return m_isInverted;
}
void PWMSpeedController::Disable() {
SetDisabled();
}
void PWMSpeedController::StopMotor() {
PWM::StopMotor();
}
void PWMSpeedController::PIDWrite(double output) {
Set(output);
}
PWMSpeedController::PWMSpeedController(int channel) : PWM(channel) {}
void PWMSpeedController::InitSendable(SendableBuilder& builder) {
builder.SetSmartDashboardType("Speed Controller");
builder.SetActuator(true);
builder.SetSafeState([=]() { SetDisabled(); });
builder.AddDoubleProperty(
"Value", [=]() { return GetSpeed(); },
[=](double value) { SetSpeed(value); });
}

View File

@@ -1,21 +0,0 @@
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include "frc/PWMTalonFX.h"
#include <hal/FRCUsageReporting.h>
#include "frc/smartdashboard/SendableRegistry.h"
using namespace frc;
PWMTalonFX::PWMTalonFX(int channel) : PWMSpeedController(channel) {
SetBounds(2.004, 1.52, 1.50, 1.48, 0.997);
SetPeriodMultiplier(kPeriodMultiplier_1X);
SetSpeed(0.0);
SetZeroLatch();
HAL_Report(HALUsageReporting::kResourceType_TalonFX, GetChannel() + 1);
SendableRegistry::GetInstance().SetName(this, "PWMTalonFX", GetChannel());
}

View File

@@ -1,21 +0,0 @@
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include "frc/PWMTalonSRX.h"
#include <hal/FRCUsageReporting.h>
#include "frc/smartdashboard/SendableRegistry.h"
using namespace frc;
PWMTalonSRX::PWMTalonSRX(int channel) : PWMSpeedController(channel) {
SetBounds(2.004, 1.52, 1.50, 1.48, 0.997);
SetPeriodMultiplier(kPeriodMultiplier_1X);
SetSpeed(0.0);
SetZeroLatch();
HAL_Report(HALUsageReporting::kResourceType_PWMTalonSRX, GetChannel() + 1);
SendableRegistry::GetInstance().SetName(this, "PWMTalonSRX", GetChannel());
}

View File

@@ -1,21 +0,0 @@
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include "frc/PWMVictorSPX.h"
#include <hal/FRCUsageReporting.h>
#include "frc/smartdashboard/SendableRegistry.h"
using namespace frc;
PWMVictorSPX::PWMVictorSPX(int channel) : PWMSpeedController(channel) {
SetBounds(2.004, 1.52, 1.50, 1.48, 0.997);
SetPeriodMultiplier(kPeriodMultiplier_1X);
SetSpeed(0.0);
SetZeroLatch();
HAL_Report(HALUsageReporting::kResourceType_PWMVictorSPX, GetChannel() + 1);
SendableRegistry::GetInstance().SetName(this, "PWMVictorSPX", GetChannel());
}

View File

@@ -7,11 +7,9 @@
#include <hal/FRCUsageReporting.h>
#include <hal/PDP.h>
#include <hal/Ports.h>
#include <wpi/SmallString.h>
#include <wpi/raw_ostream.h>
#include "frc/Errors.h"
#include "frc/SensorUtil.h"
#include "frc/WPIErrors.h"
#include "frc/smartdashboard/SendableBuilder.h"
#include "frc/smartdashboard/SendableRegistry.h"
@@ -25,10 +23,7 @@ PowerDistributionPanel::PowerDistributionPanel() : PowerDistributionPanel(0) {}
PowerDistributionPanel::PowerDistributionPanel(int module) : m_module(module) {
int32_t status = 0;
m_handle = HAL_InitializePDP(module, &status);
if (status != 0) {
wpi_setHALErrorWithRange(status, 0, HAL_GetNumPDPModules(), module);
return;
}
FRC_CheckErrorStatus(status, "Module " + wpi::Twine{module});
HAL_Report(HALUsageReporting::kResourceType_PDP, module + 1);
SendableRegistry::GetInstance().AddLW(this, "PowerDistributionPanel", module);
@@ -36,25 +31,15 @@ PowerDistributionPanel::PowerDistributionPanel(int module) : m_module(module) {
double PowerDistributionPanel::GetVoltage() const {
int32_t status = 0;
double voltage = HAL_GetPDPVoltage(m_handle, &status);
if (status) {
wpi_setWPIErrorWithContext(Timeout, "");
}
FRC_CheckErrorStatus(status, "GetVoltage");
return voltage;
}
double PowerDistributionPanel::GetTemperature() const {
int32_t status = 0;
double temperature = HAL_GetPDPTemperature(m_handle, &status);
if (status) {
wpi_setWPIErrorWithContext(Timeout, "");
}
FRC_CheckErrorStatus(status, "GetTemperature");
return temperature;
}
@@ -62,75 +47,48 @@ double PowerDistributionPanel::GetCurrent(int channel) const {
int32_t status = 0;
if (!SensorUtil::CheckPDPChannel(channel)) {
wpi::SmallString<32> str;
wpi::raw_svector_ostream buf(str);
buf << "PDP Channel " << channel;
wpi_setWPIErrorWithContext(ChannelIndexOutOfRange, buf.str());
FRC_ReportError(err::ChannelIndexOutOfRange,
"Channel " + wpi::Twine{channel});
return 0;
}
double current = HAL_GetPDPChannelCurrent(m_handle, channel, &status);
if (status) {
wpi_setWPIErrorWithContext(Timeout, "");
}
FRC_CheckErrorStatus(status, "Channel " + wpi::Twine{channel});
return current;
}
double PowerDistributionPanel::GetTotalCurrent() const {
int32_t status = 0;
double current = HAL_GetPDPTotalCurrent(m_handle, &status);
if (status) {
wpi_setWPIErrorWithContext(Timeout, "");
}
FRC_CheckErrorStatus(status, "GetTotalCurrent");
return current;
}
double PowerDistributionPanel::GetTotalPower() const {
int32_t status = 0;
double power = HAL_GetPDPTotalPower(m_handle, &status);
if (status) {
wpi_setWPIErrorWithContext(Timeout, "");
}
FRC_CheckErrorStatus(status, "GetTotalPower");
return power;
}
double PowerDistributionPanel::GetTotalEnergy() const {
int32_t status = 0;
double energy = HAL_GetPDPTotalEnergy(m_handle, &status);
if (status) {
wpi_setWPIErrorWithContext(Timeout, "");
}
FRC_CheckErrorStatus(status, "GetTotalEnergy");
return energy;
}
void PowerDistributionPanel::ResetTotalEnergy() {
int32_t status = 0;
HAL_ResetPDPTotalEnergy(m_handle, &status);
if (status) {
wpi_setWPIErrorWithContext(Timeout, "");
}
FRC_CheckErrorStatus(status, "ResetTotalEnergy");
}
void PowerDistributionPanel::ClearStickyFaults() {
int32_t status = 0;
HAL_ClearPDPStickyFaults(m_handle, &status);
if (status) {
wpi_setWPIErrorWithContext(Timeout, "");
}
FRC_CheckErrorStatus(status, "ClearStickyFaults");
}
int PowerDistributionPanel::GetModule() const {

View File

@@ -10,16 +10,14 @@
#include <networktables/NetworkTableInstance.h>
#include <wpi/StringRef.h>
#include "frc/WPIErrors.h"
using namespace frc;
// The Preferences table name
static wpi::StringRef kTableName{"Preferences"};
Preferences* Preferences::GetInstance() {
Preferences& Preferences::GetInstance() {
static Preferences instance;
return &instance;
return instance;
}
std::vector<std::string> Preferences::GetKeys() {
@@ -51,67 +49,91 @@ int64_t Preferences::GetLong(wpi::StringRef key, int64_t defaultValue) {
return static_cast<int64_t>(m_table->GetNumber(key, defaultValue));
}
void Preferences::PutString(wpi::StringRef key, wpi::StringRef value) {
void Preferences::SetString(wpi::StringRef key, wpi::StringRef value) {
auto entry = m_table->GetEntry(key);
entry.SetString(value);
entry.SetPersistent();
}
void Preferences::PutString(wpi::StringRef key, wpi::StringRef value) {
SetString(key, value);
}
void Preferences::InitString(wpi::StringRef key, wpi::StringRef value) {
auto entry = m_table->GetEntry(key);
entry.SetDefaultString(value);
}
void Preferences::PutInt(wpi::StringRef key, int value) {
void Preferences::SetInt(wpi::StringRef key, int value) {
auto entry = m_table->GetEntry(key);
entry.SetDouble(value);
entry.SetPersistent();
}
void Preferences::PutInt(wpi::StringRef key, int value) {
SetInt(key, value);
}
void Preferences::InitInt(wpi::StringRef key, int value) {
auto entry = m_table->GetEntry(key);
entry.SetDefaultDouble(value);
}
void Preferences::PutDouble(wpi::StringRef key, double value) {
void Preferences::SetDouble(wpi::StringRef key, double value) {
auto entry = m_table->GetEntry(key);
entry.SetDouble(value);
entry.SetPersistent();
}
void Preferences::PutDouble(wpi::StringRef key, double value) {
SetDouble(key, value);
}
void Preferences::InitDouble(wpi::StringRef key, double value) {
auto entry = m_table->GetEntry(key);
entry.SetDefaultDouble(value);
}
void Preferences::PutFloat(wpi::StringRef key, float value) {
void Preferences::SetFloat(wpi::StringRef key, float value) {
auto entry = m_table->GetEntry(key);
entry.SetDouble(value);
entry.SetPersistent();
}
void Preferences::PutFloat(wpi::StringRef key, float value) {
SetFloat(key, value);
}
void Preferences::InitFloat(wpi::StringRef key, float value) {
auto entry = m_table->GetEntry(key);
entry.SetDefaultDouble(value);
}
void Preferences::PutBoolean(wpi::StringRef key, bool value) {
void Preferences::SetBoolean(wpi::StringRef key, bool value) {
auto entry = m_table->GetEntry(key);
entry.SetBoolean(value);
entry.SetPersistent();
}
void Preferences::PutBoolean(wpi::StringRef key, bool value) {
SetBoolean(key, value);
}
void Preferences::InitBoolean(wpi::StringRef key, bool value) {
auto entry = m_table->GetEntry(key);
entry.SetDefaultBoolean(value);
}
void Preferences::PutLong(wpi::StringRef key, int64_t value) {
void Preferences::SetLong(wpi::StringRef key, int64_t value) {
auto entry = m_table->GetEntry(key);
entry.SetDouble(value);
entry.SetPersistent();
}
void Preferences::PutLong(wpi::StringRef key, int64_t value) {
SetLong(key, value);
}
void Preferences::InitLong(wpi::StringRef key, int64_t value) {
auto entry = m_table->GetEntry(key);
entry.SetDefaultDouble(value);
@@ -143,3 +165,5 @@ Preferences::Preferences()
NT_NOTIFY_NEW | NT_NOTIFY_IMMEDIATE);
HAL_Report(HALUsageReporting::kResourceType_Preferences, 0);
}
Preferences::~Preferences() = default;

View File

@@ -10,10 +10,11 @@
#include <hal/HALBase.h>
#include <hal/Ports.h>
#include <hal/Relay.h>
#include <wpi/StackTrace.h>
#include <wpi/raw_ostream.h>
#include "frc/Errors.h"
#include "frc/SensorUtil.h"
#include "frc/WPIErrors.h"
#include "frc/smartdashboard/SendableBuilder.h"
#include "frc/smartdashboard/SendableRegistry.h"
@@ -22,8 +23,8 @@ using namespace frc;
Relay::Relay(int channel, Relay::Direction direction)
: m_channel(channel), m_direction(direction) {
if (!SensorUtil::CheckRelayChannel(m_channel)) {
wpi_setWPIErrorWithContext(ChannelIndexOutOfRange,
"Relay Channel " + wpi::Twine(m_channel));
throw FRC_MakeError(err::ChannelIndexOutOfRange,
"Relay Channel " + wpi::Twine{m_channel});
return;
}
@@ -31,46 +32,29 @@ Relay::Relay(int channel, Relay::Direction direction)
if (m_direction == kBothDirections || m_direction == kForwardOnly) {
int32_t status = 0;
m_forwardHandle = HAL_InitializeRelayPort(portHandle, true, &status);
if (status != 0) {
wpi_setHALErrorWithRange(status, 0, HAL_GetNumRelayChannels(), channel);
m_forwardHandle = HAL_kInvalidHandle;
m_reverseHandle = HAL_kInvalidHandle;
return;
}
std::string stackTrace = wpi::GetStackTrace(1);
m_forwardHandle =
HAL_InitializeRelayPort(portHandle, true, stackTrace.c_str(), &status);
FRC_CheckErrorStatus(status, "Relay Channel " + wpi::Twine{m_channel});
HAL_Report(HALUsageReporting::kResourceType_Relay, m_channel + 1);
}
if (m_direction == kBothDirections || m_direction == kReverseOnly) {
int32_t status = 0;
m_reverseHandle = HAL_InitializeRelayPort(portHandle, false, &status);
if (status != 0) {
wpi_setHALErrorWithRange(status, 0, HAL_GetNumRelayChannels(), channel);
m_forwardHandle = HAL_kInvalidHandle;
m_reverseHandle = HAL_kInvalidHandle;
return;
}
std::string stackTrace = wpi::GetStackTrace(1);
m_reverseHandle =
HAL_InitializeRelayPort(portHandle, false, stackTrace.c_str(), &status);
FRC_CheckErrorStatus(status, "Relay Channel " + wpi::Twine{m_channel});
HAL_Report(HALUsageReporting::kResourceType_Relay, m_channel + 128);
}
int32_t status = 0;
if (m_forwardHandle != HAL_kInvalidHandle) {
HAL_SetRelay(m_forwardHandle, false, &status);
if (status != 0) {
wpi_setHALError(status);
m_forwardHandle = HAL_kInvalidHandle;
m_reverseHandle = HAL_kInvalidHandle;
return;
}
FRC_CheckErrorStatus(status, "Relay Channel " + wpi::Twine{m_channel});
}
if (m_reverseHandle != HAL_kInvalidHandle) {
HAL_SetRelay(m_reverseHandle, false, &status);
if (status != 0) {
wpi_setHALError(status);
m_forwardHandle = HAL_kInvalidHandle;
m_reverseHandle = HAL_kInvalidHandle;
return;
}
FRC_CheckErrorStatus(status, "Relay Channel " + wpi::Twine{m_channel});
}
SendableRegistry::GetInstance().AddLW(this, "Relay", m_channel);
@@ -90,10 +74,6 @@ Relay::~Relay() {
}
void Relay::Set(Relay::Value value) {
if (StatusIsFatal()) {
return;
}
int32_t status = 0;
switch (value) {
@@ -115,7 +95,7 @@ void Relay::Set(Relay::Value value) {
break;
case kForward:
if (m_direction == kReverseOnly) {
wpi_setWPIError(IncompatibleMode);
FRC_ReportError(err::IncompatibleMode, "setting forward");
break;
}
if (m_direction == kBothDirections || m_direction == kForwardOnly) {
@@ -127,7 +107,7 @@ void Relay::Set(Relay::Value value) {
break;
case kReverse:
if (m_direction == kForwardOnly) {
wpi_setWPIError(IncompatibleMode);
FRC_ReportError(err::IncompatibleMode, "setting reverse");
break;
}
if (m_direction == kBothDirections) {
@@ -139,7 +119,7 @@ void Relay::Set(Relay::Value value) {
break;
}
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Set");
}
Relay::Value Relay::Get() const {
@@ -174,7 +154,7 @@ Relay::Value Relay::Get() const {
}
}
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Get");
return value;
}

View File

@@ -4,8 +4,7 @@
#include "frc/Resource.h"
#include "frc/ErrorBase.h"
#include "frc/WPIErrors.h"
#include "frc/Errors.h"
using namespace frc;
@@ -31,19 +30,16 @@ uint32_t Resource::Allocate(const std::string& resourceDesc) {
return i;
}
}
wpi_setWPIErrorWithContext(NoAvailableResources, resourceDesc);
return std::numeric_limits<uint32_t>::max();
throw FRC_MakeError(err::NoAvailableResources, resourceDesc);
}
uint32_t Resource::Allocate(uint32_t index, const std::string& resourceDesc) {
std::scoped_lock lock(m_allocateMutex);
if (index >= m_isAllocated.size()) {
wpi_setWPIErrorWithContext(ChannelIndexOutOfRange, resourceDesc);
return std::numeric_limits<uint32_t>::max();
throw FRC_MakeError(err::ChannelIndexOutOfRange, resourceDesc);
}
if (m_isAllocated[index]) {
wpi_setWPIErrorWithContext(ResourceAlreadyAllocated, resourceDesc);
return std::numeric_limits<uint32_t>::max();
throw FRC_MakeError(err::ResourceAlreadyAllocated, resourceDesc);
}
m_isAllocated[index] = true;
return index;
@@ -55,12 +51,10 @@ void Resource::Free(uint32_t index) {
return;
}
if (index >= m_isAllocated.size()) {
wpi_setWPIError(NotAllocated);
return;
throw FRC_MakeError(err::NotAllocated, "index " + wpi::Twine{index});
}
if (!m_isAllocated[index]) {
wpi_setWPIError(NotAllocated);
return;
throw FRC_MakeError(err::NotAllocated, "index " + wpi::Twine{index});
}
m_isAllocated[index] = false;
}

View File

@@ -8,156 +8,154 @@
#include <hal/HALBase.h>
#include <hal/Power.h>
#include "frc/ErrorBase.h"
#include "frc/Errors.h"
using namespace frc;
int RobotController::GetFPGAVersion() {
int32_t status = 0;
int version = HAL_GetFPGAVersion(&status);
wpi_setGlobalHALError(status);
FRC_CheckErrorStatus(status, "GetFPGAVersion");
return version;
}
int64_t RobotController::GetFPGARevision() {
int32_t status = 0;
int64_t revision = HAL_GetFPGARevision(&status);
wpi_setGlobalHALError(status);
FRC_CheckErrorStatus(status, "GetFPGARevision");
return revision;
}
uint64_t RobotController::GetFPGATime() {
int32_t status = 0;
uint64_t time = HAL_GetFPGATime(&status);
wpi_setGlobalHALError(status);
FRC_CheckErrorStatus(status, "GetFPGATime");
return time;
}
bool RobotController::GetUserButton() {
int32_t status = 0;
bool value = HAL_GetFPGAButton(&status);
wpi_setGlobalError(status);
FRC_CheckErrorStatus(status, "GetUserButton");
return value;
}
units::volt_t RobotController::GetBatteryVoltage() {
int32_t status = 0;
double retVal = HAL_GetVinVoltage(&status);
wpi_setGlobalHALError(status);
FRC_CheckErrorStatus(status, "GetBatteryVoltage");
return units::volt_t{retVal};
}
bool RobotController::IsSysActive() {
int32_t status = 0;
bool retVal = HAL_GetSystemActive(&status);
wpi_setGlobalHALError(status);
FRC_CheckErrorStatus(status, "IsSysActive");
return retVal;
}
bool RobotController::IsBrownedOut() {
int32_t status = 0;
bool retVal = HAL_GetBrownedOut(&status);
wpi_setGlobalHALError(status);
FRC_CheckErrorStatus(status, "IsBrownedOut");
return retVal;
}
double RobotController::GetInputVoltage() {
int32_t status = 0;
double retVal = HAL_GetVinVoltage(&status);
wpi_setGlobalHALError(status);
FRC_CheckErrorStatus(status, "GetInputVoltage");
return retVal;
}
double RobotController::GetInputCurrent() {
int32_t status = 0;
double retVal = HAL_GetVinCurrent(&status);
wpi_setGlobalHALError(status);
FRC_CheckErrorStatus(status, "GetInputCurrent");
return retVal;
}
double RobotController::GetVoltage3V3() {
int32_t status = 0;
double retVal = HAL_GetUserVoltage3V3(&status);
wpi_setGlobalHALError(status);
FRC_CheckErrorStatus(status, "GetVoltage3V3");
return retVal;
}
double RobotController::GetCurrent3V3() {
int32_t status = 0;
double retVal = HAL_GetUserCurrent3V3(&status);
wpi_setGlobalHALError(status);
FRC_CheckErrorStatus(status, "GetCurrent3V3");
return retVal;
}
bool RobotController::GetEnabled3V3() {
int32_t status = 0;
bool retVal = HAL_GetUserActive3V3(&status);
wpi_setGlobalHALError(status);
FRC_CheckErrorStatus(status, "GetEnabled3V3");
return retVal;
}
int RobotController::GetFaultCount3V3() {
int32_t status = 0;
int retVal = HAL_GetUserCurrentFaults3V3(&status);
wpi_setGlobalHALError(status);
FRC_CheckErrorStatus(status, "GetFaultCount3V3");
return retVal;
}
double RobotController::GetVoltage5V() {
int32_t status = 0;
double retVal = HAL_GetUserVoltage5V(&status);
wpi_setGlobalHALError(status);
FRC_CheckErrorStatus(status, "GetVoltage5V");
return retVal;
}
double RobotController::GetCurrent5V() {
int32_t status = 0;
double retVal = HAL_GetUserCurrent5V(&status);
wpi_setGlobalHALError(status);
FRC_CheckErrorStatus(status, "GetCurrent5V");
return retVal;
}
bool RobotController::GetEnabled5V() {
int32_t status = 0;
bool retVal = HAL_GetUserActive5V(&status);
wpi_setGlobalHALError(status);
FRC_CheckErrorStatus(status, "GetEnabled5V");
return retVal;
}
int RobotController::GetFaultCount5V() {
int32_t status = 0;
int retVal = HAL_GetUserCurrentFaults5V(&status);
wpi_setGlobalHALError(status);
FRC_CheckErrorStatus(status, "GetFaultCount5V");
return retVal;
}
double RobotController::GetVoltage6V() {
int32_t status = 0;
double retVal = HAL_GetUserVoltage6V(&status);
wpi_setGlobalHALError(status);
FRC_CheckErrorStatus(status, "GetVoltage6V");
return retVal;
}
double RobotController::GetCurrent6V() {
int32_t status = 0;
double retVal = HAL_GetUserCurrent6V(&status);
wpi_setGlobalHALError(status);
FRC_CheckErrorStatus(status, "GetCurrent6V");
return retVal;
}
bool RobotController::GetEnabled6V() {
int32_t status = 0;
bool retVal = HAL_GetUserActive6V(&status);
wpi_setGlobalHALError(status);
FRC_CheckErrorStatus(status, "GetEnabled6V");
return retVal;
}
int RobotController::GetFaultCount6V() {
int32_t status = 0;
int retVal = HAL_GetUserCurrentFaults6V(&status);
wpi_setGlobalHALError(status);
FRC_CheckErrorStatus(status, "GetFaultCount6V");
return retVal;
}
@@ -170,10 +168,7 @@ CANStatus RobotController::GetCANStatus() {
uint32_t transmitErrorCount = 0;
HAL_CAN_GetCANStatus(&percentBusUtilization, &busOffCount, &txFullCount,
&receiveErrorCount, &transmitErrorCount, &status);
if (status != 0) {
wpi_setGlobalHALError(status);
return {};
}
FRC_CheckErrorStatus(status, "GetCANStatus");
return {percentBusUtilization, static_cast<int>(busOffCount),
static_cast<int>(txFullCount), static_cast<int>(receiveErrorCount),
static_cast<int>(transmitErrorCount)};

View File

@@ -1,444 +0,0 @@
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include "frc/RobotDrive.h"
#include <algorithm>
#include <cmath>
#include <hal/FRCUsageReporting.h>
#include "frc/GenericHID.h"
#include "frc/Joystick.h"
#include "frc/Talon.h"
#include "frc/Utility.h"
#include "frc/WPIErrors.h"
using namespace frc;
static std::shared_ptr<SpeedController> make_shared_nodelete(
SpeedController* ptr) {
return std::shared_ptr<SpeedController>(ptr, NullDeleter<SpeedController>());
}
RobotDrive::RobotDrive(int leftMotorChannel, int rightMotorChannel) {
InitRobotDrive();
m_rearLeftMotor = std::make_shared<Talon>(leftMotorChannel);
m_rearRightMotor = std::make_shared<Talon>(rightMotorChannel);
SetLeftRightMotorOutputs(0.0, 0.0);
}
RobotDrive::RobotDrive(int frontLeftMotor, int rearLeftMotor,
int frontRightMotor, int rearRightMotor) {
InitRobotDrive();
m_rearLeftMotor = std::make_shared<Talon>(rearLeftMotor);
m_rearRightMotor = std::make_shared<Talon>(rearRightMotor);
m_frontLeftMotor = std::make_shared<Talon>(frontLeftMotor);
m_frontRightMotor = std::make_shared<Talon>(frontRightMotor);
SetLeftRightMotorOutputs(0.0, 0.0);
}
RobotDrive::RobotDrive(SpeedController* leftMotor,
SpeedController* rightMotor) {
InitRobotDrive();
if (leftMotor == nullptr || rightMotor == nullptr) {
wpi_setWPIError(NullParameter);
m_rearLeftMotor = m_rearRightMotor = nullptr;
return;
}
m_rearLeftMotor = make_shared_nodelete(leftMotor);
m_rearRightMotor = make_shared_nodelete(rightMotor);
}
RobotDrive::RobotDrive(SpeedController& leftMotor,
SpeedController& rightMotor) {
InitRobotDrive();
m_rearLeftMotor = make_shared_nodelete(&leftMotor);
m_rearRightMotor = make_shared_nodelete(&rightMotor);
}
RobotDrive::RobotDrive(std::shared_ptr<SpeedController> leftMotor,
std::shared_ptr<SpeedController> rightMotor) {
InitRobotDrive();
if (leftMotor == nullptr || rightMotor == nullptr) {
wpi_setWPIError(NullParameter);
m_rearLeftMotor = m_rearRightMotor = nullptr;
return;
}
m_rearLeftMotor = leftMotor;
m_rearRightMotor = rightMotor;
}
RobotDrive::RobotDrive(SpeedController* frontLeftMotor,
SpeedController* rearLeftMotor,
SpeedController* frontRightMotor,
SpeedController* rearRightMotor) {
InitRobotDrive();
if (frontLeftMotor == nullptr || rearLeftMotor == nullptr ||
frontRightMotor == nullptr || rearRightMotor == nullptr) {
wpi_setWPIError(NullParameter);
return;
}
m_frontLeftMotor = make_shared_nodelete(frontLeftMotor);
m_rearLeftMotor = make_shared_nodelete(rearLeftMotor);
m_frontRightMotor = make_shared_nodelete(frontRightMotor);
m_rearRightMotor = make_shared_nodelete(rearRightMotor);
}
RobotDrive::RobotDrive(SpeedController& frontLeftMotor,
SpeedController& rearLeftMotor,
SpeedController& frontRightMotor,
SpeedController& rearRightMotor) {
InitRobotDrive();
m_frontLeftMotor = make_shared_nodelete(&frontLeftMotor);
m_rearLeftMotor = make_shared_nodelete(&rearLeftMotor);
m_frontRightMotor = make_shared_nodelete(&frontRightMotor);
m_rearRightMotor = make_shared_nodelete(&rearRightMotor);
}
RobotDrive::RobotDrive(std::shared_ptr<SpeedController> frontLeftMotor,
std::shared_ptr<SpeedController> rearLeftMotor,
std::shared_ptr<SpeedController> frontRightMotor,
std::shared_ptr<SpeedController> rearRightMotor) {
InitRobotDrive();
if (frontLeftMotor == nullptr || rearLeftMotor == nullptr ||
frontRightMotor == nullptr || rearRightMotor == nullptr) {
wpi_setWPIError(NullParameter);
return;
}
m_frontLeftMotor = frontLeftMotor;
m_rearLeftMotor = rearLeftMotor;
m_frontRightMotor = frontRightMotor;
m_rearRightMotor = rearRightMotor;
}
void RobotDrive::Drive(double outputMagnitude, double curve) {
double leftOutput, rightOutput;
static bool reported = false;
if (!reported) {
HAL_Report(HALUsageReporting::kResourceType_RobotDrive,
HALUsageReporting::kRobotDrive_ArcadeRatioCurve, GetNumMotors());
reported = true;
}
if (curve < 0) {
double value = std::log(-curve);
double ratio = (value - m_sensitivity) / (value + m_sensitivity);
if (ratio == 0) {
ratio = 0.0000000001;
}
leftOutput = outputMagnitude / ratio;
rightOutput = outputMagnitude;
} else if (curve > 0) {
double value = std::log(curve);
double ratio = (value - m_sensitivity) / (value + m_sensitivity);
if (ratio == 0) {
ratio = 0.0000000001;
}
leftOutput = outputMagnitude;
rightOutput = outputMagnitude / ratio;
} else {
leftOutput = outputMagnitude;
rightOutput = outputMagnitude;
}
SetLeftRightMotorOutputs(leftOutput, rightOutput);
}
void RobotDrive::TankDrive(GenericHID* leftStick, GenericHID* rightStick,
bool squaredInputs) {
if (leftStick == nullptr || rightStick == nullptr) {
wpi_setWPIError(NullParameter);
return;
}
TankDrive(leftStick->GetY(), rightStick->GetY(), squaredInputs);
}
void RobotDrive::TankDrive(GenericHID& leftStick, GenericHID& rightStick,
bool squaredInputs) {
TankDrive(leftStick.GetY(), rightStick.GetY(), squaredInputs);
}
void RobotDrive::TankDrive(GenericHID* leftStick, int leftAxis,
GenericHID* rightStick, int rightAxis,
bool squaredInputs) {
if (leftStick == nullptr || rightStick == nullptr) {
wpi_setWPIError(NullParameter);
return;
}
TankDrive(leftStick->GetRawAxis(leftAxis), rightStick->GetRawAxis(rightAxis),
squaredInputs);
}
void RobotDrive::TankDrive(GenericHID& leftStick, int leftAxis,
GenericHID& rightStick, int rightAxis,
bool squaredInputs) {
TankDrive(leftStick.GetRawAxis(leftAxis), rightStick.GetRawAxis(rightAxis),
squaredInputs);
}
void RobotDrive::TankDrive(double leftValue, double rightValue,
bool squaredInputs) {
static bool reported = false;
if (!reported) {
HAL_Report(HALUsageReporting::kResourceType_RobotDrive,
HALUsageReporting::kRobotDrive_Tank, GetNumMotors());
reported = true;
}
leftValue = Limit(leftValue);
rightValue = Limit(rightValue);
// square the inputs (while preserving the sign) to increase fine control
// while permitting full power
if (squaredInputs) {
leftValue = std::copysign(leftValue * leftValue, leftValue);
rightValue = std::copysign(rightValue * rightValue, rightValue);
}
SetLeftRightMotorOutputs(leftValue, rightValue);
}
void RobotDrive::ArcadeDrive(GenericHID* stick, bool squaredInputs) {
// simply call the full-featured ArcadeDrive with the appropriate values
ArcadeDrive(stick->GetY(), stick->GetX(), squaredInputs);
}
void RobotDrive::ArcadeDrive(GenericHID& stick, bool squaredInputs) {
// simply call the full-featured ArcadeDrive with the appropriate values
ArcadeDrive(stick.GetY(), stick.GetX(), squaredInputs);
}
void RobotDrive::ArcadeDrive(GenericHID* moveStick, int moveAxis,
GenericHID* rotateStick, int rotateAxis,
bool squaredInputs) {
double moveValue = moveStick->GetRawAxis(moveAxis);
double rotateValue = rotateStick->GetRawAxis(rotateAxis);
ArcadeDrive(moveValue, rotateValue, squaredInputs);
}
void RobotDrive::ArcadeDrive(GenericHID& moveStick, int moveAxis,
GenericHID& rotateStick, int rotateAxis,
bool squaredInputs) {
double moveValue = moveStick.GetRawAxis(moveAxis);
double rotateValue = rotateStick.GetRawAxis(rotateAxis);
ArcadeDrive(moveValue, rotateValue, squaredInputs);
}
void RobotDrive::ArcadeDrive(double moveValue, double rotateValue,
bool squaredInputs) {
static bool reported = false;
if (!reported) {
HAL_Report(HALUsageReporting::kResourceType_RobotDrive,
HALUsageReporting::kRobotDrive_ArcadeStandard, GetNumMotors());
reported = true;
}
// local variables to hold the computed PWM values for the motors
double leftMotorOutput;
double rightMotorOutput;
moveValue = Limit(moveValue);
rotateValue = Limit(rotateValue);
// square the inputs (while preserving the sign) to increase fine control
// while permitting full power
if (squaredInputs) {
moveValue = std::copysign(moveValue * moveValue, moveValue);
rotateValue = std::copysign(rotateValue * rotateValue, rotateValue);
}
if (moveValue > 0.0) {
if (rotateValue > 0.0) {
leftMotorOutput = moveValue - rotateValue;
rightMotorOutput = std::max(moveValue, rotateValue);
} else {
leftMotorOutput = std::max(moveValue, -rotateValue);
rightMotorOutput = moveValue + rotateValue;
}
} else {
if (rotateValue > 0.0) {
leftMotorOutput = -std::max(-moveValue, rotateValue);
rightMotorOutput = moveValue + rotateValue;
} else {
leftMotorOutput = moveValue - rotateValue;
rightMotorOutput = -std::max(-moveValue, -rotateValue);
}
}
SetLeftRightMotorOutputs(leftMotorOutput, rightMotorOutput);
}
void RobotDrive::MecanumDrive_Cartesian(double x, double y, double rotation,
double gyroAngle) {
static bool reported = false;
if (!reported) {
HAL_Report(HALUsageReporting::kResourceType_RobotDrive,
HALUsageReporting::kRobotDrive_MecanumCartesian, GetNumMotors());
reported = true;
}
double xIn = x;
double yIn = y;
// Negate y for the joystick.
yIn = -yIn;
// Compensate for gyro angle.
RotateVector(xIn, yIn, gyroAngle);
double wheelSpeeds[kMaxNumberOfMotors];
wheelSpeeds[kFrontLeftMotor] = xIn + yIn + rotation;
wheelSpeeds[kFrontRightMotor] = -xIn + yIn - rotation;
wheelSpeeds[kRearLeftMotor] = -xIn + yIn + rotation;
wheelSpeeds[kRearRightMotor] = xIn + yIn - rotation;
Normalize(wheelSpeeds);
m_frontLeftMotor->Set(wheelSpeeds[kFrontLeftMotor] * m_maxOutput);
m_frontRightMotor->Set(wheelSpeeds[kFrontRightMotor] * m_maxOutput);
m_rearLeftMotor->Set(wheelSpeeds[kRearLeftMotor] * m_maxOutput);
m_rearRightMotor->Set(wheelSpeeds[kRearRightMotor] * m_maxOutput);
Feed();
}
void RobotDrive::MecanumDrive_Polar(double magnitude, double direction,
double rotation) {
static bool reported = false;
if (!reported) {
HAL_Report(HALUsageReporting::kResourceType_RobotDrive,
HALUsageReporting::kRobotDrive_MecanumPolar, GetNumMotors());
reported = true;
}
// Normalized for full power along the Cartesian axes.
magnitude = Limit(magnitude) * std::sqrt(2.0);
// The rollers are at 45 degree angles.
double dirInRad = (direction + 45.0) * 3.14159 / 180.0;
double cosD = std::cos(dirInRad);
double sinD = std::sin(dirInRad);
double wheelSpeeds[kMaxNumberOfMotors];
wheelSpeeds[kFrontLeftMotor] = sinD * magnitude + rotation;
wheelSpeeds[kFrontRightMotor] = cosD * magnitude - rotation;
wheelSpeeds[kRearLeftMotor] = cosD * magnitude + rotation;
wheelSpeeds[kRearRightMotor] = sinD * magnitude - rotation;
Normalize(wheelSpeeds);
m_frontLeftMotor->Set(wheelSpeeds[kFrontLeftMotor] * m_maxOutput);
m_frontRightMotor->Set(wheelSpeeds[kFrontRightMotor] * m_maxOutput);
m_rearLeftMotor->Set(wheelSpeeds[kRearLeftMotor] * m_maxOutput);
m_rearRightMotor->Set(wheelSpeeds[kRearRightMotor] * m_maxOutput);
Feed();
}
void RobotDrive::HolonomicDrive(double magnitude, double direction,
double rotation) {
MecanumDrive_Polar(magnitude, direction, rotation);
}
void RobotDrive::SetLeftRightMotorOutputs(double leftOutput,
double rightOutput) {
wpi_assert(m_rearLeftMotor != nullptr && m_rearRightMotor != nullptr);
if (m_frontLeftMotor != nullptr) {
m_frontLeftMotor->Set(Limit(leftOutput) * m_maxOutput);
}
m_rearLeftMotor->Set(Limit(leftOutput) * m_maxOutput);
if (m_frontRightMotor != nullptr) {
m_frontRightMotor->Set(-Limit(rightOutput) * m_maxOutput);
}
m_rearRightMotor->Set(-Limit(rightOutput) * m_maxOutput);
Feed();
}
void RobotDrive::SetInvertedMotor(MotorType motor, bool isInverted) {
if (motor < 0 || motor > 3) {
wpi_setWPIError(InvalidMotorIndex);
return;
}
switch (motor) {
case kFrontLeftMotor:
m_frontLeftMotor->SetInverted(isInverted);
break;
case kFrontRightMotor:
m_frontRightMotor->SetInverted(isInverted);
break;
case kRearLeftMotor:
m_rearLeftMotor->SetInverted(isInverted);
break;
case kRearRightMotor:
m_rearRightMotor->SetInverted(isInverted);
break;
}
}
void RobotDrive::SetSensitivity(double sensitivity) {
m_sensitivity = sensitivity;
}
void RobotDrive::SetMaxOutput(double maxOutput) {
m_maxOutput = maxOutput;
}
void RobotDrive::GetDescription(wpi::raw_ostream& desc) const {
desc << "RobotDrive";
}
void RobotDrive::StopMotor() {
if (m_frontLeftMotor != nullptr) {
m_frontLeftMotor->StopMotor();
}
if (m_frontRightMotor != nullptr) {
m_frontRightMotor->StopMotor();
}
if (m_rearLeftMotor != nullptr) {
m_rearLeftMotor->StopMotor();
}
if (m_rearRightMotor != nullptr) {
m_rearRightMotor->StopMotor();
}
Feed();
}
void RobotDrive::InitRobotDrive() {
SetSafetyEnabled(true);
}
double RobotDrive::Limit(double number) {
if (number > 1.0) {
return 1.0;
}
if (number < -1.0) {
return -1.0;
}
return number;
}
void RobotDrive::Normalize(double* wheelSpeeds) {
double maxMagnitude = std::fabs(wheelSpeeds[0]);
for (int i = 1; i < kMaxNumberOfMotors; i++) {
double temp = std::fabs(wheelSpeeds[i]);
if (maxMagnitude < temp) {
maxMagnitude = temp;
}
}
if (maxMagnitude > 1.0) {
for (int i = 0; i < kMaxNumberOfMotors; i++) {
wheelSpeeds[i] = wheelSpeeds[i] / maxMagnitude;
}
}
}
void RobotDrive::RotateVector(double& x, double& y, double angle) {
double cosA = std::cos(angle * (3.14159 / 180.0));
double sinA = std::sin(angle * (3.14159 / 180.0));
double xOut = x * cosA - y * sinA;
double yOut = x * sinA + y * cosA;
x = xOut;
y = yOut;
}

View File

@@ -14,8 +14,8 @@
#include <wpi/mutex.h>
#include "frc/DigitalSource.h"
#include "frc/Errors.h"
#include "frc/Notifier.h"
#include "frc/WPIErrors.h"
using namespace frc;
@@ -77,9 +77,7 @@ void SPI::Accumulator::Update() {
// get amount of data available
int32_t numToRead =
HAL_ReadSPIAutoReceivedData(m_port, m_buf, 0, 0, &status);
if (status != 0) {
return; // error reading
}
FRC_CheckErrorStatus(status, "ReadSPIAutoReceivedData");
// only get whole responses; +1 is for timestamp
numToRead -= numToRead % m_xferSize;
@@ -93,9 +91,7 @@ void SPI::Accumulator::Update() {
// read buffered data
HAL_ReadSPIAutoReceivedData(m_port, m_buf, numToRead, 0, &status);
if (status != 0) {
return; // error reading
}
FRC_CheckErrorStatus(status, "ReadSPIAutoReceivedData");
// loop over all responses
for (int32_t off = 0; off < numToRead; off += m_xferSize) {
@@ -162,7 +158,7 @@ void SPI::Accumulator::Update() {
SPI::SPI(Port port) : m_port(static_cast<HAL_SPIPort>(port)) {
int32_t status = 0;
HAL_InitializeSPI(m_port, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "InitializeSPI");
HAL_Report(HALUsageReporting::kResourceType_SPI,
static_cast<uint8_t>(port) + 1);
@@ -219,13 +215,13 @@ void SPI::SetClockActiveHigh() {
void SPI::SetChipSelectActiveHigh() {
int32_t status = 0;
HAL_SetSPIChipSelectActiveHigh(m_port, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "SetChipSelectActiveHigh");
}
void SPI::SetChipSelectActiveLow() {
int32_t status = 0;
HAL_SetSPIChipSelectActiveLow(m_port, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "SetChipSelectActiveLow");
}
int SPI::Write(uint8_t* data, int size) {
@@ -255,26 +251,26 @@ int SPI::Transaction(uint8_t* dataToSend, uint8_t* dataReceived, int size) {
void SPI::InitAuto(int bufferSize) {
int32_t status = 0;
HAL_InitSPIAuto(m_port, bufferSize, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "InitAuto");
}
void SPI::FreeAuto() {
int32_t status = 0;
HAL_FreeSPIAuto(m_port, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "FreeAuto");
}
void SPI::SetAutoTransmitData(wpi::ArrayRef<uint8_t> dataToSend, int zeroSize) {
int32_t status = 0;
HAL_SetSPIAutoTransmitData(m_port, dataToSend.data(), dataToSend.size(),
zeroSize, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "SetAutoTransmitData");
}
void SPI::StartAutoRate(units::second_t period) {
int32_t status = 0;
HAL_StartSPIAutoRate(m_port, period.to<double>(), &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "StartAutoRate");
}
void SPI::StartAutoRate(double period) {
@@ -287,19 +283,19 @@ void SPI::StartAutoTrigger(DigitalSource& source, bool rising, bool falling) {
static_cast<HAL_AnalogTriggerType>(
source.GetAnalogTriggerTypeForRouting()),
rising, falling, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "StartAutoTrigger");
}
void SPI::StopAuto() {
int32_t status = 0;
HAL_StopSPIAuto(m_port, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "StopAuto");
}
void SPI::ForceAutoRead() {
int32_t status = 0;
HAL_ForceSPIAutoRead(m_port, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "ForceAutoRead");
}
int SPI::ReadAutoReceivedData(uint32_t* buffer, int numToRead,
@@ -307,7 +303,7 @@ int SPI::ReadAutoReceivedData(uint32_t* buffer, int numToRead,
int32_t status = 0;
int32_t val = HAL_ReadSPIAutoReceivedData(m_port, buffer, numToRead,
timeout.to<double>(), &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "ReadAutoReceivedData");
return val;
}
@@ -318,7 +314,7 @@ int SPI::ReadAutoReceivedData(uint32_t* buffer, int numToRead, double timeout) {
int SPI::GetAutoDroppedCount() {
int32_t status = 0;
int32_t val = HAL_GetSPIAutoDroppedCount(m_port, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "GetAutoDroppedCount");
return val;
}
@@ -327,7 +323,7 @@ void SPI::ConfigureAutoStall(HAL_SPIPort port, int csToSclkTicks,
int32_t status = 0;
HAL_ConfigureSPIAutoStall(m_port, csToSclkTicks, stallTicks, pow2BytesPerRead,
&status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "ConfigureAutoStall");
}
void SPI::InitAccumulator(units::second_t period, int cmd, int xferSize,

View File

@@ -9,6 +9,8 @@
#include <hal/FRCUsageReporting.h>
#include <hal/SerialPort.h>
#include "frc/Errors.h"
using namespace frc;
SerialPort::SerialPort(int baudRate, Port port, int dataBits,
@@ -18,19 +20,17 @@ SerialPort::SerialPort(int baudRate, Port port, int dataBits,
m_portHandle =
HAL_InitializeSerialPort(static_cast<HAL_SerialPort>(port), &status);
wpi_setHALError(status);
// Don't continue if initialization failed
if (status < 0) {
return;
}
FRC_CheckErrorStatus(status, "Port " + wpi::Twine{static_cast<int>(port)});
HAL_SetSerialBaudRate(m_portHandle, baudRate, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "SetSerialBaudRate " + wpi::Twine{baudRate});
HAL_SetSerialDataBits(m_portHandle, dataBits, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "SetSerialDataBits " + wpi::Twine{dataBits});
HAL_SetSerialParity(m_portHandle, parity, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(
status, "SetSerialParity " + wpi::Twine{static_cast<int>(parity)});
HAL_SetSerialStopBits(m_portHandle, stopBits, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(
status, "SetSerialStopBits " + wpi::Twine{static_cast<int>(stopBits)});
// Set the default timeout to 5 seconds.
SetTimeout(5.0);
@@ -54,19 +54,17 @@ SerialPort::SerialPort(int baudRate, const wpi::Twine& portName, Port port,
m_portHandle = HAL_InitializeSerialPortDirect(
static_cast<HAL_SerialPort>(port), portNameC, &status);
wpi_setHALError(status);
// Don't continue if initialization failed
if (status < 0) {
return;
}
FRC_CheckErrorStatus(status, "Port " + wpi::Twine{static_cast<int>(port)});
HAL_SetSerialBaudRate(m_portHandle, baudRate, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "SetSerialBaudRate " + wpi::Twine{baudRate});
HAL_SetSerialDataBits(m_portHandle, dataBits, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "SetSerialDataBits " + wpi::Twine{dataBits});
HAL_SetSerialParity(m_portHandle, parity, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(
status, "SetSerialParity " + wpi::Twine{static_cast<int>(parity)});
HAL_SetSerialStopBits(m_portHandle, stopBits, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(
status, "SetSerialStopBits " + wpi::Twine{static_cast<int>(stopBits)});
// Set the default timeout to 5 seconds.
SetTimeout(5.0);
@@ -83,38 +81,40 @@ SerialPort::SerialPort(int baudRate, const wpi::Twine& portName, Port port,
SerialPort::~SerialPort() {
int32_t status = 0;
HAL_CloseSerial(m_portHandle, &status);
wpi_setHALError(status);
FRC_ReportError(status, "CloseSerial");
}
void SerialPort::SetFlowControl(SerialPort::FlowControl flowControl) {
int32_t status = 0;
HAL_SetSerialFlowControl(m_portHandle, flowControl, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(
status, "SetFlowControl " + wpi::Twine{static_cast<int>(flowControl)});
}
void SerialPort::EnableTermination(char terminator) {
int32_t status = 0;
HAL_EnableSerialTermination(m_portHandle, terminator, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(
status, "EnableTermination " + wpi::Twine{static_cast<int>(terminator)});
}
void SerialPort::DisableTermination() {
int32_t status = 0;
HAL_DisableSerialTermination(m_portHandle, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "DisableTermination");
}
int SerialPort::GetBytesReceived() {
int32_t status = 0;
int retVal = HAL_GetSerialBytesReceived(m_portHandle, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "GetBytesReceived");
return retVal;
}
int SerialPort::Read(char* buffer, int count) {
int32_t status = 0;
int retVal = HAL_ReadSerial(m_portHandle, buffer, count, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Read");
return retVal;
}
@@ -126,42 +126,43 @@ int SerialPort::Write(wpi::StringRef buffer) {
int32_t status = 0;
int retVal =
HAL_WriteSerial(m_portHandle, buffer.data(), buffer.size(), &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Write");
return retVal;
}
void SerialPort::SetTimeout(double timeout) {
int32_t status = 0;
HAL_SetSerialTimeout(m_portHandle, timeout, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "SetTimeout");
}
void SerialPort::SetReadBufferSize(int size) {
int32_t status = 0;
HAL_SetSerialReadBufferSize(m_portHandle, size, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "SetReadBufferSize " + wpi::Twine{size});
}
void SerialPort::SetWriteBufferSize(int size) {
int32_t status = 0;
HAL_SetSerialWriteBufferSize(m_portHandle, size, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "SetWriteBufferSize " + wpi::Twine{size});
}
void SerialPort::SetWriteBufferMode(SerialPort::WriteBufferMode mode) {
int32_t status = 0;
HAL_SetSerialWriteMode(m_portHandle, mode, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(
status, "SetWriteBufferMode " + wpi::Twine{static_cast<int>(mode)});
}
void SerialPort::Flush() {
int32_t status = 0;
HAL_FlushSerial(m_portHandle, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Flush");
}
void SerialPort::Reset() {
int32_t status = 0;
HAL_ClearSerial(m_portHandle, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Reset");
}

View File

@@ -11,8 +11,8 @@
#include <hal/Ports.h>
#include <hal/Solenoid.h>
#include "frc/Errors.h"
#include "frc/SensorUtil.h"
#include "frc/WPIErrors.h"
#include "frc/smartdashboard/SendableBuilder.h"
#include "frc/smartdashboard/SendableRegistry.h"
@@ -24,24 +24,19 @@ Solenoid::Solenoid(int channel)
Solenoid::Solenoid(int moduleNumber, int channel)
: SolenoidBase(moduleNumber), m_channel(channel) {
if (!SensorUtil::CheckSolenoidModule(m_moduleNumber)) {
wpi_setWPIErrorWithContext(ModuleIndexOutOfRange,
"Solenoid Module " + wpi::Twine(m_moduleNumber));
return;
throw FRC_MakeError(err::ModuleIndexOutOfRange,
"Solenoid Module " + wpi::Twine{m_moduleNumber});
}
if (!SensorUtil::CheckSolenoidChannel(m_channel)) {
wpi_setWPIErrorWithContext(ChannelIndexOutOfRange,
"Solenoid Channel " + wpi::Twine(m_channel));
return;
throw FRC_MakeError(err::ChannelIndexOutOfRange,
"Solenoid Channel " + wpi::Twine{m_channel});
}
int32_t status = 0;
m_solenoidHandle = HAL_InitializeSolenoidPort(
HAL_GetPortWithModule(moduleNumber, channel), &status);
if (status != 0) {
wpi_setHALErrorWithRange(status, 0, HAL_GetNumSolenoidChannels(), channel);
m_solenoidHandle = HAL_kInvalidHandle;
return;
}
FRC_CheckErrorStatus(status, "Solenoid Module " + wpi::Twine{m_moduleNumber} +
" Channel " + wpi::Twine{m_channel});
HAL_Report(HALUsageReporting::kResourceType_Solenoid, m_channel + 1,
m_moduleNumber + 1);
@@ -54,23 +49,15 @@ Solenoid::~Solenoid() {
}
void Solenoid::Set(bool on) {
if (StatusIsFatal()) {
return;
}
int32_t status = 0;
HAL_SetSolenoid(m_solenoidHandle, on, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Set");
}
bool Solenoid::Get() const {
if (StatusIsFatal()) {
return false;
}
int32_t status = 0;
bool value = HAL_GetSolenoid(m_solenoidHandle, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "Get");
return value;
}
@@ -90,21 +77,15 @@ bool Solenoid::IsBlackListed() const {
void Solenoid::SetPulseDuration(double durationSeconds) {
int32_t durationMS = durationSeconds * 1000;
if (StatusIsFatal()) {
return;
}
int32_t status = 0;
HAL_SetOneShotDuration(m_solenoidHandle, durationMS, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "SetPulseDuration");
}
void Solenoid::StartPulse() {
if (StatusIsFatal()) {
return;
}
int32_t status = 0;
HAL_FireOneShot(m_solenoidHandle, &status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "StartPulse");
}
void Solenoid::InitSendable(SendableBuilder& builder) {

View File

@@ -7,13 +7,15 @@
#include <hal/FRCUsageReporting.h>
#include <hal/Solenoid.h>
#include "frc/Errors.h"
using namespace frc;
int SolenoidBase::GetAll(int module) {
int value = 0;
int32_t status = 0;
value = HAL_GetAllSolenoids(module, &status);
wpi_setGlobalHALError(status);
FRC_CheckErrorStatus(status, "Module " + wpi::Twine{module});
return value;
}
@@ -23,7 +25,9 @@ int SolenoidBase::GetAll() const {
int SolenoidBase::GetPCMSolenoidBlackList(int module) {
int32_t status = 0;
return HAL_GetPCMSolenoidBlackList(module, &status);
int rv = HAL_GetPCMSolenoidBlackList(module, &status);
FRC_CheckErrorStatus(status, "Module " + wpi::Twine{module});
return rv;
}
int SolenoidBase::GetPCMSolenoidBlackList() const {
@@ -32,7 +36,9 @@ int SolenoidBase::GetPCMSolenoidBlackList() const {
bool SolenoidBase::GetPCMSolenoidVoltageStickyFault(int module) {
int32_t status = 0;
return HAL_GetPCMSolenoidVoltageStickyFault(module, &status);
bool rv = HAL_GetPCMSolenoidVoltageStickyFault(module, &status);
FRC_CheckErrorStatus(status, "Module " + wpi::Twine{module});
return rv;
}
bool SolenoidBase::GetPCMSolenoidVoltageStickyFault() const {
@@ -41,7 +47,9 @@ bool SolenoidBase::GetPCMSolenoidVoltageStickyFault() const {
bool SolenoidBase::GetPCMSolenoidVoltageFault(int module) {
int32_t status = 0;
return HAL_GetPCMSolenoidVoltageFault(module, &status);
bool rv = HAL_GetPCMSolenoidVoltageFault(module, &status);
FRC_CheckErrorStatus(status, "Module " + wpi::Twine{module});
return rv;
}
bool SolenoidBase::GetPCMSolenoidVoltageFault() const {
@@ -50,7 +58,8 @@ bool SolenoidBase::GetPCMSolenoidVoltageFault() const {
void SolenoidBase::ClearAllPCMStickyFaults(int module) {
int32_t status = 0;
return HAL_ClearAllPCMStickyFaults(module, &status);
HAL_ClearAllPCMStickyFaults(module, &status);
FRC_CheckErrorStatus(status, "Module " + wpi::Twine{module});
}
void SolenoidBase::ClearAllPCMStickyFaults() {

View File

@@ -60,10 +60,6 @@ void SpeedControllerGroup::StopMotor() {
}
}
void SpeedControllerGroup::PIDWrite(double output) {
Set(output);
}
void SpeedControllerGroup::InitSendable(SendableBuilder& builder) {
builder.SetSmartDashboardType("Speed Controller");
builder.SetActuator(true);

View File

@@ -7,7 +7,7 @@
#include <hal/FRCUsageReporting.h>
#include <hal/Threads.h>
#include "frc/ErrorBase.h"
#include "frc/Errors.h"
namespace frc {
@@ -16,7 +16,7 @@ int GetThreadPriority(std::thread& thread, bool* isRealTime) {
HAL_Bool rt = false;
auto native = thread.native_handle();
auto ret = HAL_GetThreadPriority(&native, &rt, &status);
wpi_setGlobalHALError(status);
FRC_CheckErrorStatus(status, "GetThreadPriority");
*isRealTime = rt;
return ret;
}
@@ -25,7 +25,7 @@ int GetCurrentThreadPriority(bool* isRealTime) {
int32_t status = 0;
HAL_Bool rt = false;
auto ret = HAL_GetCurrentThreadPriority(&rt, &status);
wpi_setGlobalHALError(status);
FRC_CheckErrorStatus(status, "GetCurrentThreadPriority");
*isRealTime = rt;
return ret;
}
@@ -34,14 +34,14 @@ bool SetThreadPriority(std::thread& thread, bool realTime, int priority) {
int32_t status = 0;
auto native = thread.native_handle();
auto ret = HAL_SetThreadPriority(&native, realTime, priority, &status);
wpi_setGlobalHALError(status);
FRC_CheckErrorStatus(status, "SetThreadPriority");
return ret;
}
bool SetCurrentThreadPriority(bool realTime, int priority) {
int32_t status = 0;
auto ret = HAL_SetCurrentThreadPriority(realTime, priority, &status);
wpi_setGlobalHALError(status);
FRC_CheckErrorStatus(status, "SetCurrentThreadPriority");
return ret;
}

View File

@@ -12,9 +12,9 @@
#include <hal/FRCUsageReporting.h>
#include <hal/Notifier.h>
#include "frc/Errors.h"
#include "frc/Timer.h"
#include "frc/Utility.h"
#include "frc/WPIErrors.h"
using namespace frc;
@@ -39,7 +39,7 @@ void TimedRobot::StartCompetition() {
HAL_UpdateNotifierAlarm(
m_notifier, static_cast<uint64_t>(callback.expirationTime * 1e6),
&status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "UpdateNotifierAlarm");
uint64_t curTime = HAL_WaitForNotifierAlarm(m_notifier, &status);
if (curTime == 0 || status != 0) {
@@ -69,10 +69,6 @@ void TimedRobot::EndCompetition() {
HAL_StopNotifier(m_notifier, &status);
}
units::second_t TimedRobot::GetPeriod() const {
return units::second_t(m_period);
}
TimedRobot::TimedRobot(double period) : TimedRobot(units::second_t(period)) {}
TimedRobot::TimedRobot(units::second_t period) : IterativeRobotBase(period) {
@@ -81,7 +77,7 @@ TimedRobot::TimedRobot(units::second_t period) : IterativeRobotBase(period) {
int32_t status = 0;
m_notifier = HAL_InitializeNotifier(&status);
wpi_setHALError(status);
FRC_CheckErrorStatus(status, "InitializeNotifier");
HAL_SetNotifierName(m_notifier, "TimedRobot", &status);
HAL_Report(HALUsageReporting::kResourceType_Framework,
@@ -92,7 +88,7 @@ TimedRobot::~TimedRobot() {
int32_t status = 0;
HAL_StopNotifier(m_notifier, &status);
wpi_setHALError(status);
FRC_ReportError(status, "StopNotifier");
HAL_CleanNotifier(m_notifier, &status);
}

View File

@@ -12,9 +12,9 @@
#include "frc/Counter.h"
#include "frc/DigitalInput.h"
#include "frc/DigitalOutput.h"
#include "frc/Errors.h"
#include "frc/Timer.h"
#include "frc/Utility.h"
#include "frc/WPIErrors.h"
#include "frc/smartdashboard/SendableBuilder.h"
#include "frc/smartdashboard/SendableRegistry.h"
@@ -26,47 +26,41 @@ std::atomic<bool> Ultrasonic::m_automaticEnabled{false};
std::vector<Ultrasonic*> Ultrasonic::m_sensors;
std::thread Ultrasonic::m_thread;
Ultrasonic::Ultrasonic(int pingChannel, int echoChannel, DistanceUnit units)
Ultrasonic::Ultrasonic(int pingChannel, int echoChannel)
: m_pingChannel(std::make_shared<DigitalOutput>(pingChannel)),
m_echoChannel(std::make_shared<DigitalInput>(echoChannel)),
m_counter(m_echoChannel) {
m_units = units;
Initialize();
auto& registry = SendableRegistry::GetInstance();
registry.AddChild(this, m_pingChannel.get());
registry.AddChild(this, m_echoChannel.get());
}
Ultrasonic::Ultrasonic(DigitalOutput* pingChannel, DigitalInput* echoChannel,
DistanceUnit units)
Ultrasonic::Ultrasonic(DigitalOutput* pingChannel, DigitalInput* echoChannel)
: m_pingChannel(pingChannel, NullDeleter<DigitalOutput>()),
m_echoChannel(echoChannel, NullDeleter<DigitalInput>()),
m_counter(m_echoChannel) {
if (pingChannel == nullptr || echoChannel == nullptr) {
wpi_setWPIError(NullParameter);
m_units = units;
return;
if (!pingChannel) {
throw FRC_MakeError(err::NullParameter, "pingChannel");
}
if (!echoChannel) {
throw FRC_MakeError(err::NullParameter, "echoChannel");
}
m_units = units;
Initialize();
}
Ultrasonic::Ultrasonic(DigitalOutput& pingChannel, DigitalInput& echoChannel,
DistanceUnit units)
Ultrasonic::Ultrasonic(DigitalOutput& pingChannel, DigitalInput& echoChannel)
: m_pingChannel(&pingChannel, NullDeleter<DigitalOutput>()),
m_echoChannel(&echoChannel, NullDeleter<DigitalInput>()),
m_counter(m_echoChannel) {
m_units = units;
Initialize();
}
Ultrasonic::Ultrasonic(std::shared_ptr<DigitalOutput> pingChannel,
std::shared_ptr<DigitalInput> echoChannel,
DistanceUnit units)
std::shared_ptr<DigitalInput> echoChannel)
: m_pingChannel(std::move(pingChannel)),
m_echoChannel(std::move(echoChannel)),
m_counter(m_echoChannel) {
m_units = units;
Initialize();
}
@@ -164,31 +158,6 @@ void Ultrasonic::SetEnabled(bool enable) {
m_enabled = enable;
}
void Ultrasonic::SetDistanceUnits(DistanceUnit units) {
m_units = units;
}
Ultrasonic::DistanceUnit Ultrasonic::GetDistanceUnits() const {
return m_units;
}
double Ultrasonic::PIDGet() {
switch (m_units) {
case Ultrasonic::kInches:
return GetRangeInches();
case Ultrasonic::kMilliMeters:
return GetRangeMM();
default:
return 0.0;
}
}
void Ultrasonic::SetPIDSourceType(PIDSourceType pidSource) {
if (wpi_assert(pidSource == PIDSourceType::kDisplacement)) {
m_pidSource = pidSource;
}
}
void Ultrasonic::InitSendable(SendableBuilder& builder) {
builder.SetSmartDashboardType("Ultrasonic");
builder.AddDoubleProperty(

View File

@@ -1,21 +0,0 @@
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include "frc/VictorSP.h"
#include <hal/FRCUsageReporting.h>
#include "frc/smartdashboard/SendableRegistry.h"
using namespace frc;
VictorSP::VictorSP(int channel) : PWMSpeedController(channel) {
SetBounds(2.004, 1.52, 1.50, 1.48, 0.997);
SetPeriodMultiplier(kPeriodMultiplier_1X);
SetSpeed(0.0);
SetZeroLatch();
HAL_Report(HALUsageReporting::kResourceType_VictorSP, GetChannel() + 1);
SendableRegistry::GetInstance().SetName(this, "VictorSP", GetChannel());
}

View File

@@ -14,6 +14,7 @@
#include <wpi/raw_ostream.h>
#include "frc/DriverStation.h"
#include "frc/Errors.h"
#include "frc2/Timer.h"
using namespace frc;
@@ -47,7 +48,7 @@ class Watchdog::Impl {
Watchdog::Impl::Impl() {
int32_t status = 0;
m_notifier = HAL_InitializeNotifier(&status);
wpi_setGlobalHALError(status);
FRC_CheckErrorStatus(status, "starting watchdog notifier");
HAL_SetNotifierName(m_notifier, "Watchdog", &status);
m_thread = std::thread([=] { Main(); });
@@ -58,7 +59,7 @@ Watchdog::Impl::~Impl() {
// atomically set handle to 0, then clean
HAL_NotifierHandle handle = m_notifier.exchange(0);
HAL_StopNotifier(handle, &status);
wpi_setGlobalHALError(status);
FRC_ReportError(status, "stopping watchdog notifier");
// Join the thread to ensure the handler has exited.
if (m_thread.joinable()) {
@@ -84,7 +85,7 @@ void Watchdog::Impl::UpdateAlarm() {
1e6),
&status);
}
wpi_setGlobalHALError(status);
FRC_CheckErrorStatus(status, "updating watchdog notifier alarm");
}
void Watchdog::Impl::Main() {
@@ -141,7 +142,11 @@ Watchdog::Watchdog(units::second_t timeout, std::function<void()> callback)
: m_timeout(timeout), m_callback(std::move(callback)), m_impl(GetImpl()) {}
Watchdog::~Watchdog() {
Disable();
try {
Disable();
} catch (const RuntimeError& e) {
e.Report();
}
}
Watchdog::Watchdog(Watchdog&& rhs) {

View File

@@ -15,6 +15,14 @@
using namespace frc;
#if defined(_MSC_VER)
#pragma warning(disable : 4996) // was declared deprecated
#elif defined(__clang__)
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
#elif defined(__GNUC__)
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif
DifferentialDrive::DifferentialDrive(SpeedController& leftMotor,
SpeedController& rightMotor)
: m_leftMotor(&leftMotor), m_rightMotor(&rightMotor) {

View File

@@ -16,6 +16,14 @@
using namespace frc;
#if defined(_MSC_VER)
#pragma warning(disable : 4996) // was declared deprecated
#elif defined(__clang__)
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
#elif defined(__GNUC__)
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif
KilloughDrive::KilloughDrive(SpeedController& leftMotor,
SpeedController& rightMotor,
SpeedController& backMotor)

View File

@@ -17,6 +17,14 @@
using namespace frc;
#if defined(_MSC_VER)
#pragma warning(disable : 4996) // was declared deprecated
#elif defined(__clang__)
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
#elif defined(__GNUC__)
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif
MecanumDrive::MecanumDrive(SpeedController& frontLeftMotor,
SpeedController& rearLeftMotor,
SpeedController& frontRightMotor,

View File

@@ -11,7 +11,7 @@
#include <hal/FRCUsageReporting.h>
#include "frc/Base.h"
#include "frc/SpeedController.h"
#include "frc/motorcontrol/MotorController.h"
using namespace frc;

View File

@@ -1,27 +0,0 @@
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include "frc/filters/Filter.h"
#include "frc/Base.h"
using namespace frc;
Filter::Filter(PIDSource& source)
: m_source(std::shared_ptr<PIDSource>(&source, NullDeleter<PIDSource>())) {}
Filter::Filter(std::shared_ptr<PIDSource> source)
: m_source(std::move(source)) {}
void Filter::SetPIDSourceType(PIDSourceType pidSource) {
m_source->SetPIDSourceType(pidSource);
}
PIDSourceType Filter::GetPIDSourceType() const {
return m_source->GetPIDSourceType();
}
double Filter::PIDGetSource() {
return m_source->PIDGet();
}

View File

@@ -1,133 +0,0 @@
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include "frc/filters/LinearDigitalFilter.h"
#include <cassert>
#include <cmath>
#include <hal/FRCUsageReporting.h>
using namespace frc;
LinearDigitalFilter::LinearDigitalFilter(PIDSource& source,
wpi::ArrayRef<double> ffGains,
wpi::ArrayRef<double> fbGains)
: Filter(source),
m_inputs(ffGains.size()),
m_outputs(fbGains.size()),
m_inputGains(ffGains),
m_outputGains(fbGains) {
static int instances = 0;
instances++;
HAL_Report(HALUsageReporting::kResourceType_LinearFilter, instances);
}
LinearDigitalFilter::LinearDigitalFilter(PIDSource& source,
std::initializer_list<double> ffGains,
std::initializer_list<double> fbGains)
: LinearDigitalFilter(source,
wpi::makeArrayRef(ffGains.begin(), ffGains.end()),
wpi::makeArrayRef(fbGains.begin(), fbGains.end())) {}
LinearDigitalFilter::LinearDigitalFilter(std::shared_ptr<PIDSource> source,
wpi::ArrayRef<double> ffGains,
wpi::ArrayRef<double> fbGains)
: Filter(source),
m_inputs(ffGains.size()),
m_outputs(fbGains.size()),
m_inputGains(ffGains),
m_outputGains(fbGains) {
static int instances = 0;
instances++;
HAL_Report(HALUsageReporting::kResourceType_LinearFilter, instances);
}
LinearDigitalFilter::LinearDigitalFilter(std::shared_ptr<PIDSource> source,
std::initializer_list<double> ffGains,
std::initializer_list<double> fbGains)
: LinearDigitalFilter(source,
wpi::makeArrayRef(ffGains.begin(), ffGains.end()),
wpi::makeArrayRef(fbGains.begin(), fbGains.end())) {}
LinearDigitalFilter LinearDigitalFilter::SinglePoleIIR(PIDSource& source,
double timeConstant,
double period) {
double gain = std::exp(-period / timeConstant);
return LinearDigitalFilter(source, {1.0 - gain}, {-gain});
}
LinearDigitalFilter LinearDigitalFilter::HighPass(PIDSource& source,
double timeConstant,
double period) {
double gain = std::exp(-period / timeConstant);
return LinearDigitalFilter(source, {gain, -gain}, {-gain});
}
LinearDigitalFilter LinearDigitalFilter::MovingAverage(PIDSource& source,
int taps) {
assert(taps > 0);
std::vector<double> gains(taps, 1.0 / taps);
return LinearDigitalFilter(source, gains, {});
}
LinearDigitalFilter LinearDigitalFilter::SinglePoleIIR(
std::shared_ptr<PIDSource> source, double timeConstant, double period) {
double gain = std::exp(-period / timeConstant);
return LinearDigitalFilter(std::move(source), {1.0 - gain}, {-gain});
}
LinearDigitalFilter LinearDigitalFilter::HighPass(
std::shared_ptr<PIDSource> source, double timeConstant, double period) {
double gain = std::exp(-period / timeConstant);
return LinearDigitalFilter(std::move(source), {gain, -gain}, {-gain});
}
LinearDigitalFilter LinearDigitalFilter::MovingAverage(
std::shared_ptr<PIDSource> source, int taps) {
assert(taps > 0);
std::vector<double> gains(taps, 1.0 / taps);
return LinearDigitalFilter(std::move(source), gains, {});
}
double LinearDigitalFilter::Get() const {
double retVal = 0.0;
// Calculate the new value
for (size_t i = 0; i < m_inputGains.size(); i++) {
retVal += m_inputs[i] * m_inputGains[i];
}
for (size_t i = 0; i < m_outputGains.size(); i++) {
retVal -= m_outputs[i] * m_outputGains[i];
}
return retVal;
}
void LinearDigitalFilter::Reset() {
m_inputs.reset();
m_outputs.reset();
}
double LinearDigitalFilter::PIDGet() {
double retVal = 0.0;
// Rotate the inputs
m_inputs.push_front(PIDGetSource());
// Calculate the new value
for (size_t i = 0; i < m_inputGains.size(); i++) {
retVal += m_inputs[i] * m_inputGains[i];
}
for (size_t i = 0; i < m_outputGains.size(); i++) {
retVal -= m_outputs[i] * m_outputGains[i];
}
// Rotate the outputs
m_outputs.push_front(retVal);
return retVal;
}

View File

@@ -1,15 +0,0 @@
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include "frc/interfaces/Potentiometer.h"
#include "frc/Utility.h"
using namespace frc;
void Potentiometer::SetPIDSourceType(PIDSourceType pidSource) {
if (wpi_assert(pidSource == PIDSourceType::kDisplacement)) {
m_pidSource = pidSource;
}
}

View File

@@ -61,9 +61,9 @@ std::shared_ptr<LiveWindow::Impl::Component> LiveWindow::Impl::GetOrAdd(
return data;
}
LiveWindow* LiveWindow::GetInstance() {
LiveWindow& LiveWindow::GetInstance() {
static LiveWindow instance;
return &instance;
return instance;
}
void LiveWindow::EnableTelemetry(Sendable* sendable) {
@@ -154,7 +154,7 @@ void LiveWindow::UpdateValuesUnsafe() {
return;
}
auto ssTable = m_impl->liveWindowTable->GetSubTable(cbdata.subsystem);
std::shared_ptr<NetworkTable> table;
std::shared_ptr<nt::NetworkTable> table;
// Treat name==subsystem as top level of subsystem
if (cbdata.name == cbdata.subsystem) {
table = ssTable;

View File

@@ -2,20 +2,17 @@
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include "frc/DMC60.h"
#include "frc/motorcontrol/DMC60.h"
#include <hal/FRCUsageReporting.h>
#include "frc/smartdashboard/SendableRegistry.h"
using namespace frc;
DMC60::DMC60(int channel) : PWMSpeedController(channel) {
SetBounds(2.004, 1.52, 1.50, 1.48, 0.997);
SetPeriodMultiplier(kPeriodMultiplier_1X);
SetSpeed(0.0);
SetZeroLatch();
DMC60::DMC60(int channel) : PWMMotorController("DMC60", channel) {
m_pwm.SetBounds(2.004, 1.52, 1.50, 1.48, 0.997);
m_pwm.SetPeriodMultiplier(PWM::kPeriodMultiplier_1X);
m_pwm.SetSpeed(0.0);
m_pwm.SetZeroLatch();
HAL_Report(HALUsageReporting::kResourceType_DigilentDMC60, GetChannel() + 1);
SendableRegistry::GetInstance().SetName(this, "DMC60", GetChannel());
}

View File

@@ -2,20 +2,17 @@
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include "frc/Jaguar.h"
#include "frc/motorcontrol/Jaguar.h"
#include <hal/FRCUsageReporting.h>
#include "frc/smartdashboard/SendableRegistry.h"
using namespace frc;
Jaguar::Jaguar(int channel) : PWMSpeedController(channel) {
SetBounds(2.31, 1.55, 1.507, 1.454, 0.697);
SetPeriodMultiplier(kPeriodMultiplier_1X);
SetSpeed(0.0);
SetZeroLatch();
Jaguar::Jaguar(int channel) : PWMMotorController("Jaguar", channel) {
m_pwm.SetBounds(2.31, 1.55, 1.507, 1.454, 0.697);
m_pwm.SetPeriodMultiplier(PWM::kPeriodMultiplier_1X);
m_pwm.SetSpeed(0.0);
m_pwm.SetZeroLatch();
HAL_Report(HALUsageReporting::kResourceType_Jaguar, GetChannel() + 1);
SendableRegistry::GetInstance().SetName(this, "Jaguar", GetChannel());
}

View File

@@ -0,0 +1,69 @@
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include "frc/motorcontrol/MotorControllerGroup.h"
#include "frc/smartdashboard/SendableBuilder.h"
#include "frc/smartdashboard/SendableRegistry.h"
using namespace frc;
// Can't use a delegated constructor here because of an MSVC bug.
// https://developercommunity.visualstudio.com/content/problem/583/compiler-bug-with-delegating-a-constructor.html
MotorControllerGroup::MotorControllerGroup(
std::vector<std::reference_wrapper<MotorController>>&& motorControllers)
: m_motorControllers(std::move(motorControllers)) {
Initialize();
}
void MotorControllerGroup::Initialize() {
for (auto& motorController : m_motorControllers) {
SendableRegistry::GetInstance().AddChild(this, &motorController.get());
}
static int instances = 0;
++instances;
SendableRegistry::GetInstance().Add(this, "MotorControllerGroup", instances);
}
void MotorControllerGroup::Set(double speed) {
for (auto motorController : m_motorControllers) {
motorController.get().Set(m_isInverted ? -speed : speed);
}
}
double MotorControllerGroup::Get() const {
if (!m_motorControllers.empty()) {
return m_motorControllers.front().get().Get() * (m_isInverted ? -1 : 1);
}
return 0.0;
}
void MotorControllerGroup::SetInverted(bool isInverted) {
m_isInverted = isInverted;
}
bool MotorControllerGroup::GetInverted() const {
return m_isInverted;
}
void MotorControllerGroup::Disable() {
for (auto motorController : m_motorControllers) {
motorController.get().Disable();
}
}
void MotorControllerGroup::StopMotor() {
for (auto motorController : m_motorControllers) {
motorController.get().StopMotor();
}
}
void MotorControllerGroup::InitSendable(SendableBuilder& builder) {
builder.SetSmartDashboardType("Motor Controller");
builder.SetActuator(true);
builder.SetSafeState([=]() { StopMotor(); });
builder.AddDoubleProperty(
"Value", [=]() { return Get(); }, [=](double value) { Set(value); });
}

View File

@@ -2,9 +2,10 @@
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include "frc/NidecBrushless.h"
#include "frc/motorcontrol/NidecBrushless.h"
#include <hal/FRCUsageReporting.h>
#include <wpi/raw_ostream.h>
#include "frc/smartdashboard/SendableBuilder.h"
#include "frc/smartdashboard/SendableRegistry.h"
@@ -58,10 +59,6 @@ void NidecBrushless::Enable() {
m_disabled = false;
}
void NidecBrushless::PIDWrite(double output) {
Set(output);
}
void NidecBrushless::StopMotor() {
m_dio.UpdateDutyCycle(0.5);
m_pwm.SetDisabled();

View File

@@ -0,0 +1,56 @@
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include "frc/motorcontrol/PWMMotorController.h"
#include <wpi/raw_ostream.h>
#include "frc/smartdashboard/SendableBuilder.h"
using namespace frc;
void PWMMotorController::Set(double speed) {
m_pwm.SetSpeed(m_isInverted ? -speed : speed);
}
double PWMMotorController::Get() const {
return m_pwm.GetSpeed() * (m_isInverted ? -1.0 : 1.0);
}
void PWMMotorController::SetInverted(bool isInverted) {
m_isInverted = isInverted;
}
bool PWMMotorController::GetInverted() const {
return m_isInverted;
}
void PWMMotorController::Disable() {
m_pwm.SetDisabled();
}
void PWMMotorController::StopMotor() {
Disable();
}
void PWMMotorController::GetDescription(wpi::raw_ostream& desc) const {
desc << "PWM " << GetChannel();
}
int PWMMotorController::GetChannel() const {
return m_pwm.GetChannel();
}
PWMMotorController::PWMMotorController(const wpi::Twine& name, int channel)
: m_pwm(channel, false) {
SendableRegistry::GetInstance().AddLW(this, name, channel);
}
void PWMMotorController::InitSendable(SendableBuilder& builder) {
builder.SetSmartDashboardType("Motor Controller");
builder.SetActuator(true);
builder.SetSafeState([=] { Disable(); });
builder.AddDoubleProperty(
"Value", [=] { return Get(); }, [=](double value) { Set(value); });
}

View File

@@ -2,7 +2,7 @@
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include "frc/PWMSparkMax.h"
#include "frc/motorcontrol/PWMSparkMax.h"
#include <hal/FRCUsageReporting.h>
@@ -10,12 +10,12 @@
using namespace frc;
PWMSparkMax::PWMSparkMax(int channel) : PWMSpeedController(channel) {
SetBounds(2.003, 1.55, 1.50, 1.46, 0.999);
SetPeriodMultiplier(kPeriodMultiplier_1X);
SetSpeed(0.0);
SetZeroLatch();
PWMSparkMax::PWMSparkMax(int channel)
: PWMMotorController("PWMSparkMax", channel) {
m_pwm.SetBounds(2.003, 1.55, 1.50, 1.46, 0.999);
m_pwm.SetPeriodMultiplier(PWM::kPeriodMultiplier_1X);
m_pwm.SetSpeed(0.0);
m_pwm.SetZeroLatch();
HAL_Report(HALUsageReporting::kResourceType_RevSparkMaxPWM, GetChannel() + 1);
SendableRegistry::GetInstance().SetName(this, "PWMSparkMax", GetChannel());
}

View File

@@ -0,0 +1,19 @@
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include "frc/motorcontrol/PWMTalonFX.h"
#include <hal/FRCUsageReporting.h>
using namespace frc;
PWMTalonFX::PWMTalonFX(int channel)
: PWMMotorController("PWMTalonFX", channel) {
m_pwm.SetBounds(2.004, 1.52, 1.50, 1.48, 0.997);
m_pwm.SetPeriodMultiplier(PWM::kPeriodMultiplier_1X);
m_pwm.SetSpeed(0.0);
m_pwm.SetZeroLatch();
HAL_Report(HALUsageReporting::kResourceType_TalonFX, GetChannel() + 1);
}

View File

@@ -0,0 +1,19 @@
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include "frc/motorcontrol/PWMTalonSRX.h"
#include <hal/FRCUsageReporting.h>
using namespace frc;
PWMTalonSRX::PWMTalonSRX(int channel)
: PWMMotorController("PWMTalonSRX", channel) {
m_pwm.SetBounds(2.004, 1.52, 1.50, 1.48, 0.997);
m_pwm.SetPeriodMultiplier(PWM::kPeriodMultiplier_1X);
m_pwm.SetSpeed(0.0);
m_pwm.SetZeroLatch();
HAL_Report(HALUsageReporting::kResourceType_PWMTalonSRX, GetChannel() + 1);
}

View File

@@ -2,20 +2,17 @@
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include "frc/PWMVenom.h"
#include "frc/motorcontrol/PWMVenom.h"
#include <hal/FRCUsageReporting.h>
#include "frc/smartdashboard/SendableRegistry.h"
using namespace frc;
PWMVenom::PWMVenom(int channel) : PWMSpeedController(channel) {
SetBounds(2.004, 1.52, 1.50, 1.48, 0.997);
SetPeriodMultiplier(kPeriodMultiplier_1X);
SetSpeed(0.0);
SetZeroLatch();
PWMVenom::PWMVenom(int channel) : PWMMotorController("PWMVenom", channel) {
m_pwm.SetBounds(2.004, 1.52, 1.50, 1.48, 0.997);
m_pwm.SetPeriodMultiplier(PWM::kPeriodMultiplier_1X);
m_pwm.SetSpeed(0.0);
m_pwm.SetZeroLatch();
HAL_Report(HALUsageReporting::kResourceType_FusionVenom, GetChannel() + 1);
SendableRegistry::GetInstance().SetName(this, "PWMVenom", GetChannel());
}

View File

@@ -0,0 +1,19 @@
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include "frc/motorcontrol/PWMVictorSPX.h"
#include <hal/FRCUsageReporting.h>
using namespace frc;
PWMVictorSPX::PWMVictorSPX(int channel)
: PWMMotorController("PWMVictorSPX", channel) {
m_pwm.SetBounds(2.004, 1.52, 1.50, 1.48, 0.997);
m_pwm.SetPeriodMultiplier(PWM::kPeriodMultiplier_1X);
m_pwm.SetSpeed(0.0);
m_pwm.SetZeroLatch();
HAL_Report(HALUsageReporting::kResourceType_PWMVictorSPX, GetChannel() + 1);
}

View File

@@ -2,21 +2,18 @@
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include "frc/SD540.h"
#include "frc/motorcontrol/SD540.h"
#include <hal/FRCUsageReporting.h>
#include "frc/smartdashboard/SendableRegistry.h"
using namespace frc;
SD540::SD540(int channel) : PWMSpeedController(channel) {
SetBounds(2.05, 1.55, 1.50, 1.44, 0.94);
SetPeriodMultiplier(kPeriodMultiplier_1X);
SetSpeed(0.0);
SetZeroLatch();
SD540::SD540(int channel) : PWMMotorController("SD540", channel) {
m_pwm.SetBounds(2.05, 1.55, 1.50, 1.44, 0.94);
m_pwm.SetPeriodMultiplier(PWM::kPeriodMultiplier_1X);
m_pwm.SetSpeed(0.0);
m_pwm.SetZeroLatch();
HAL_Report(HALUsageReporting::kResourceType_MindsensorsSD540,
GetChannel() + 1);
SendableRegistry::GetInstance().SetName(this, "SD540", GetChannel());
}

View File

@@ -2,20 +2,17 @@
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include "frc/Spark.h"
#include "frc/motorcontrol/Spark.h"
#include <hal/FRCUsageReporting.h>
#include "frc/smartdashboard/SendableRegistry.h"
using namespace frc;
Spark::Spark(int channel) : PWMSpeedController(channel) {
SetBounds(2.003, 1.55, 1.50, 1.46, 0.999);
SetPeriodMultiplier(kPeriodMultiplier_1X);
SetSpeed(0.0);
SetZeroLatch();
Spark::Spark(int channel) : PWMMotorController("Spark", channel) {
m_pwm.SetBounds(2.003, 1.55, 1.50, 1.46, 0.999);
m_pwm.SetPeriodMultiplier(PWM::kPeriodMultiplier_1X);
m_pwm.SetSpeed(0.0);
m_pwm.SetZeroLatch();
HAL_Report(HALUsageReporting::kResourceType_RevSPARK, GetChannel() + 1);
SendableRegistry::GetInstance().SetName(this, "Spark", GetChannel());
}

View File

@@ -2,20 +2,17 @@
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include "frc/Talon.h"
#include "frc/motorcontrol/Talon.h"
#include <hal/FRCUsageReporting.h>
#include "frc/smartdashboard/SendableRegistry.h"
using namespace frc;
Talon::Talon(int channel) : PWMSpeedController(channel) {
SetBounds(2.037, 1.539, 1.513, 1.487, 0.989);
SetPeriodMultiplier(kPeriodMultiplier_1X);
SetSpeed(0.0);
SetZeroLatch();
Talon::Talon(int channel) : PWMMotorController("Talon", channel) {
m_pwm.SetBounds(2.037, 1.539, 1.513, 1.487, 0.989);
m_pwm.SetPeriodMultiplier(PWM::kPeriodMultiplier_1X);
m_pwm.SetSpeed(0.0);
m_pwm.SetZeroLatch();
HAL_Report(HALUsageReporting::kResourceType_Talon, GetChannel() + 1);
SendableRegistry::GetInstance().SetName(this, "Talon", GetChannel());
}

View File

@@ -2,20 +2,17 @@
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include "frc/Victor.h"
#include "frc/motorcontrol/Victor.h"
#include <hal/FRCUsageReporting.h>
#include "frc/smartdashboard/SendableRegistry.h"
using namespace frc;
Victor::Victor(int channel) : PWMSpeedController(channel) {
SetBounds(2.027, 1.525, 1.507, 1.49, 1.026);
SetPeriodMultiplier(kPeriodMultiplier_2X);
SetSpeed(0.0);
SetZeroLatch();
Victor::Victor(int channel) : PWMMotorController("Victor", channel) {
m_pwm.SetBounds(2.027, 1.525, 1.507, 1.49, 1.026);
m_pwm.SetPeriodMultiplier(PWM::kPeriodMultiplier_2X);
m_pwm.SetSpeed(0.0);
m_pwm.SetZeroLatch();
HAL_Report(HALUsageReporting::kResourceType_Victor, GetChannel() + 1);
SendableRegistry::GetInstance().SetName(this, "Victor", GetChannel());
}

View File

@@ -0,0 +1,18 @@
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include "frc/motorcontrol/VictorSP.h"
#include <hal/FRCUsageReporting.h>
using namespace frc;
VictorSP::VictorSP(int channel) : PWMMotorController("VictorSP", channel) {
m_pwm.SetBounds(2.004, 1.52, 1.50, 1.48, 0.997);
m_pwm.SetPeriodMultiplier(PWM::kPeriodMultiplier_1X);
m_pwm.SetSpeed(0.0);
m_pwm.SetZeroLatch();
HAL_Report(HALUsageReporting::kResourceType_VictorSP, GetChannel() + 1);
}

View File

@@ -7,6 +7,7 @@
#include <wpi/SmallVector.h>
#include <wpi/raw_ostream.h>
#include "frc/Errors.h"
#include "frc/shuffleboard/ComplexWidget.h"
#include "frc/shuffleboard/ShuffleboardComponent.h"
#include "frc/shuffleboard/ShuffleboardLayout.h"
@@ -56,8 +57,8 @@ ShuffleboardLayout& ShuffleboardContainer::GetLayout(const wpi::Twine& title) {
wpi::SmallVector<char, 16> storage;
auto titleRef = title.toStringRef(storage);
if (m_layouts.count(titleRef) == 0) {
wpi_setWPIErrorWithContext(
InvalidParameter, "No layout with the given title has been defined");
throw FRC_MakeError(err::InvalidParameter,
"No layout with the given title has been defined");
}
return *m_layouts[titleRef];
}

View File

@@ -19,7 +19,8 @@ MechanismLigament2d::MechanismLigament2d(const wpi::Twine& name, double length,
SetColor(color);
}
void MechanismLigament2d::UpdateEntries(std::shared_ptr<NetworkTable> table) {
void MechanismLigament2d::UpdateEntries(
std::shared_ptr<nt::NetworkTable> table) {
table->GetEntry(".type").SetString("line");
m_colorEntry = table->GetEntry("color");

View File

@@ -13,7 +13,7 @@ const std::string& MechanismObject2d::GetName() const {
return m_name;
}
void MechanismObject2d::Update(std::shared_ptr<NetworkTable> table) {
void MechanismObject2d::Update(std::shared_ptr<nt::NetworkTable> table) {
std::scoped_lock lock(m_mutex);
m_table = table;
UpdateEntries(m_table);

View File

@@ -23,7 +23,7 @@ void MechanismRoot2d::SetPosition(double x, double y) {
Flush();
}
void MechanismRoot2d::UpdateEntries(std::shared_ptr<NetworkTable> table) {
void MechanismRoot2d::UpdateEntries(std::shared_ptr<nt::NetworkTable> table) {
m_posEntry = table->GetEntry(kPosition);
Flush();
}

View File

@@ -1,17 +0,0 @@
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include "frc/smartdashboard/SendableBase.h"
#include "frc/smartdashboard/SendableRegistry.h"
using namespace frc;
SendableBase::SendableBase(bool addLiveWindow) {
if (addLiveWindow) {
SendableRegistry::GetInstance().AddLW(this, "");
} else {
SendableRegistry::GetInstance().Add(this, "");
}
}

View File

@@ -352,7 +352,7 @@ Sendable* SendableRegistry::GetSendable(UID uid) {
}
void SendableRegistry::Publish(UID sendableUid,
std::shared_ptr<NetworkTable> table) {
std::shared_ptr<nt::NetworkTable> table) {
std::scoped_lock lock(m_impl->mutex);
if (sendableUid == 0 || (sendableUid - 1) >= m_impl->components.size() ||
!m_impl->components[sendableUid - 1]) {

View File

@@ -10,7 +10,7 @@
#include <wpi/StringMap.h>
#include <wpi/mutex.h>
#include "frc/WPIErrors.h"
#include "frc/Errors.h"
#include "frc/smartdashboard/SendableRegistry.h"
using namespace frc;
@@ -85,9 +85,8 @@ nt::NetworkTableEntry SmartDashboard::GetEntry(wpi::StringRef key) {
}
void SmartDashboard::PutData(wpi::StringRef key, Sendable* data) {
if (data == nullptr) {
wpi_setGlobalWPIErrorWithContext(NullParameter, "value");
return;
if (!data) {
throw FRC_MakeError(err::NullParameter, "value");
}
auto& inst = Singleton::GetInstance();
std::scoped_lock lock(inst.tablesToDataMutex);
@@ -103,9 +102,8 @@ void SmartDashboard::PutData(wpi::StringRef key, Sendable* data) {
}
void SmartDashboard::PutData(Sendable* value) {
if (value == nullptr) {
wpi_setGlobalWPIErrorWithContext(NullParameter, "value");
return;
if (!value) {
throw FRC_MakeError(err::NullParameter, "value");
}
auto name = SendableRegistry::GetInstance().GetName(value);
if (!name.empty()) {
@@ -118,8 +116,7 @@ Sendable* SmartDashboard::GetData(wpi::StringRef key) {
std::scoped_lock lock(inst.tablesToDataMutex);
auto it = inst.tablesToData.find(key);
if (it == inst.tablesToData.end()) {
wpi_setGlobalWPIErrorWithContext(SmartDashboardMissingKey, key);
return nullptr;
throw FRC_MakeError(err::SmartDashboardMissingKey, key);
}
return SendableRegistry::GetInstance().GetSendable(it->getValue());
}