SCRIPT Move cc files

This commit is contained in:
PJ Reiniger
2025-11-07 19:55:39 -05:00
committed by Peter Johnson
parent 10b4a0c971
commit 7ca1be9bae
1197 changed files with 0 additions and 0 deletions

View File

@@ -0,0 +1,55 @@
// 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.
#pragma once
#include <hal/SimDevice.h>
namespace frc {
class ADXL345_I2C;
namespace sim {
/**
* Class to control a simulated ADXL345.
*/
class ADXL345Sim {
public:
/**
* Constructs from a ADXL345_I2C object.
*
* @param accel ADXL345 accel to simulate
*/
explicit ADXL345Sim(const ADXL345_I2C& accel);
/**
* Sets the X acceleration.
*
* @param accel The X acceleration.
*/
void SetX(double accel);
/**
* Sets the Y acceleration.
*
* @param accel The Y acceleration.
*/
void SetY(double accel);
/**
* Sets the Z acceleration.
*
* @param accel The Z acceleration.
*/
void SetZ(double accel);
private:
hal::SimDouble m_simX;
hal::SimDouble m_simY;
hal::SimDouble m_simZ;
};
} // namespace sim
} // namespace frc

View File

@@ -0,0 +1,168 @@
// 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.
#pragma once
#include <memory>
#include "frc/simulation/CallbackStore.h"
struct HAL_AddressableLEDData;
namespace frc {
class AddressableLED;
namespace sim {
/**
* Class to control a simulated addressable LED.
*/
class AddressableLEDSim {
public:
/**
* Constructs an addressable LED for a specific channel.
*
* @param channel output channel
*/
explicit AddressableLEDSim(int channel);
/**
* Constructs from an AddressableLED object.
*
* @param addressableLED AddressableLED to simulate
*/
explicit AddressableLEDSim(const AddressableLED& addressableLED);
/**
* Register a callback on the Initialized property.
*
* @param callback the callback that will be called whenever the Initialized
* property is changed
* @param initialNotify if true, the callback will be run on the initial value
* @return the CallbackStore object storing this callback
*/
[[nodiscard]]
std::unique_ptr<CallbackStore> RegisterInitializedCallback(
NotifyCallback callback, bool initialNotify);
/**
* Check if initialized.
*
* @return true if initialized
*/
bool GetInitialized() const;
/**
* Change the Initialized value of the LED strip.
*
* @param initialized the new value
*/
void SetInitialized(bool initialized);
/**
* Register a callback on the start.
*
* @param callback the callback that will be called whenever the start
* is changed
* @param initialNotify if true, the callback will be run on the initial value
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
std::unique_ptr<CallbackStore> RegisterStartCallback(NotifyCallback callback,
bool initialNotify);
/**
* Get the start.
*
* @return the start
*/
int GetStart() const;
/**
* Change the start.
*
* @param start the new start
*/
void SetStart(int start);
/**
* Register a callback on the length.
*
* @param callback the callback that will be called whenever the length is
* changed
* @param initialNotify if true, the callback will be run on the initial value
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
std::unique_ptr<CallbackStore> RegisterLengthCallback(NotifyCallback callback,
bool initialNotify);
/**
* Get the length of the LED strip.
*
* @return the length
*/
int GetLength() const;
/**
* Change the length of the LED strip.
*
* @param length the new value
*/
void SetLength(int length);
/**
* Get the LED data.
*
* @param data output parameter to fill with LED data
* @return the length of the LED data
*/
int GetData(struct HAL_AddressableLEDData* data) const;
/**
* Change the LED data.
*
* @param data the new data
*/
void SetData(struct HAL_AddressableLEDData* data);
/**
* Register a callback on the LED data.
*
* @param callback the callback that will be called whenever the LED data is
* changed
* @param initialNotify if true, the callback will be run on the initial value
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
static std::unique_ptr<CallbackStore> RegisterDataCallback(
ConstBufferCallback callback, bool initialNotify);
/**
* Get the global LED data.
*
* @param start the start of the LED data
* @param length the length of the LED data
* @param data output parameter to fill with LED data
* @return the length of the LED data
*/
static int GetGlobalData(int start, int length,
struct HAL_AddressableLEDData* data);
/**
* Change the global LED data.
*
* @param start the start of the LED data
* @param length the length of the LED data
* @param data the new data
*/
static void SetGlobalData(int start, int length,
struct HAL_AddressableLEDData* data);
private:
int m_channel;
};
} // namespace sim
} // namespace frc

View File

@@ -0,0 +1,46 @@
// 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.
#pragma once
#include <hal/SimDevice.h>
#include <units/angle.h>
#include "frc/geometry/Rotation2d.h"
namespace frc {
class AnalogEncoder;
namespace sim {
/**
* Class to control a simulated analog encoder.
*/
class AnalogEncoderSim {
public:
/**
* Constructs from an AnalogEncoder object.
*
* @param encoder AnalogEncoder to simulate
*/
explicit AnalogEncoderSim(const AnalogEncoder& encoder);
/**
* Set the position.
*
* @param value The position.
*/
void Set(double value);
/**
* Get the simulated position.
*/
double Get();
private:
hal::SimDouble m_positionSim;
};
} // namespace sim
} // namespace frc

View File

@@ -0,0 +1,149 @@
// 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.
#pragma once
#include <memory>
#include "frc/simulation/CallbackStore.h"
namespace frc {
class AnalogInput;
namespace sim {
/**
* Class to control a simulated analog input.
*/
class AnalogInputSim {
public:
/**
* Constructs from an AnalogInput object.
*
* @param analogInput AnalogInput to simulate
*/
explicit AnalogInputSim(const AnalogInput& analogInput);
/**
* Constructs from an analog input channel number.
*
* @param channel Channel number
*/
explicit AnalogInputSim(int channel);
/**
* Register a callback on whether the analog input is initialized.
*
* @param callback the callback that will be called whenever the analog input
* is initialized
* @param initialNotify if true, the callback will be run on the initial value
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
std::unique_ptr<CallbackStore> RegisterInitializedCallback(
NotifyCallback callback, bool initialNotify);
/**
* Check if this analog input has been initialized.
*
* @return true if initialized
*/
bool GetInitialized() const;
/**
* Change whether this analog input has been initialized.
*
* @param initialized the new value
*/
void SetInitialized(bool initialized);
/**
* Register a callback on the number of average bits.
*
* @param callback the callback that will be called whenever the number of
* average bits is changed
* @param initialNotify if true, the callback will be run on the initial value
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
std::unique_ptr<CallbackStore> RegisterAverageBitsCallback(
NotifyCallback callback, bool initialNotify);
/**
* Get the number of average bits.
*
* @return the number of average bits
*/
int GetAverageBits() const;
/**
* Change the number of average bits.
*
* @param averageBits the new value
*/
void SetAverageBits(int averageBits);
/**
* Register a callback on the amount of oversampling bits.
*
* @param callback the callback that will be called whenever the oversampling
* bits are changed
* @param initialNotify if true, the callback will be run on the initial value
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
std::unique_ptr<CallbackStore> RegisterOversampleBitsCallback(
NotifyCallback callback, bool initialNotify);
/**
* Get the amount of oversampling bits.
*
* @return the amount of oversampling bits
*/
int GetOversampleBits() const;
/**
* Change the amount of oversampling bits.
*
* @param oversampleBits the new value
*/
void SetOversampleBits(int oversampleBits);
/**
* Register a callback on the voltage.
*
* @param callback the callback that will be called whenever the voltage is
* changed
* @param initialNotify if true, the callback will be run on the initial value
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
std::unique_ptr<CallbackStore> RegisterVoltageCallback(
NotifyCallback callback, bool initialNotify);
/**
* Get the voltage.
*
* @return the voltage
*/
double GetVoltage() const;
/**
* Change the voltage.
*
* @param voltage the new value
*/
void SetVoltage(double voltage);
/**
* Reset all simulation data for this object.
*/
void ResetData();
private:
int m_index;
};
} // namespace sim
} // namespace frc

View File

@@ -0,0 +1,92 @@
// 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.
#pragma once
#include <algorithm>
#include <numeric>
#include <span>
#include <units/current.h>
#include <units/impedance.h>
#include <units/voltage.h>
namespace frc::sim {
/**
* A utility class to simulate the robot battery.
*/
class BatterySim {
public:
/**
* Calculate the loaded battery voltage. Use this with
* RoboRioSim::SetVInVoltage(double) to set the simulated battery voltage,
* which can then be retrieved with the RobotController::GetBatteryVoltage()
* method.
*
* @param nominalVoltage The nominal battery voltage. Usually 12v.
* @param resistance The forward resistance of the battery. Most batteries
* are at or below 20 milliohms.
* @param currents The currents drawn from the battery.
* @return The battery's voltage under load.
*/
static units::volt_t Calculate(units::volt_t nominalVoltage,
units::ohm_t resistance,
std::span<const units::ampere_t> currents) {
return std::max(0_V, nominalVoltage - std::accumulate(currents.begin(),
currents.end(), 0_A) *
resistance);
}
/**
* Calculate the loaded battery voltage. Use this with
* RoboRioSim::SetVInVoltage(double) to set the simulated battery voltage,
* which can then be retrieved with the RobotController::GetBatteryVoltage()
* method.
*
* @param nominalVoltage The nominal battery voltage. Usually 12v.
* @param resistance The forward resistance of the battery. Most batteries
* are at or below 20 milliohms.
* @param currents The currents drawn from the battery.
* @return The battery's voltage under load.
*/
static units::volt_t Calculate(
units::volt_t nominalVoltage, units::ohm_t resistance,
std::initializer_list<units::ampere_t> currents) {
return std::max(0_V, nominalVoltage - std::accumulate(currents.begin(),
currents.end(), 0_A) *
resistance);
}
/**
* Calculate the loaded battery voltage. Use this with
* RoboRioSimSetVInVoltage(double) to set the simulated battery voltage, which
* can then be retrieved with the RobotController::GetBatteryVoltage() method.
* This function assumes a nominal voltage of 12V and a resistance of 20
* milliohms (0.020 ohms).
*
* @param currents The currents drawn from the battery.
* @return The battery's voltage under load.
*/
static units::volt_t Calculate(std::span<const units::ampere_t> currents) {
return Calculate(12_V, 0.02_Ohm, currents);
}
/**
* Calculate the loaded battery voltage. Use this with
* RoboRioSimSetVInVoltage(double) to set the simulated battery voltage, which
* can then be retrieved with the RobotController::GetBatteryVoltage() method.
* This function assumes a nominal voltage of 12V and a resistance of 20
* milliohms (0.020 ohms).
*
* @param currents The currents drawn from the battery.
* @return The battery's voltage under load.
*/
static units::volt_t Calculate(
std::initializer_list<units::ampere_t> currents) {
return Calculate(12_V, 0.02_Ohm, currents);
}
};
} // namespace frc::sim

View File

@@ -0,0 +1,143 @@
// 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.
#pragma once
#include <memory>
#include "frc/PneumaticsBase.h"
#include "frc/simulation/CallbackStore.h"
#include "frc/simulation/PneumaticsBaseSim.h"
namespace frc::sim {
/**
* Class to control a simulated Pneumatic Control Module (PCM).
*/
class CTREPCMSim : public PneumaticsBaseSim {
public:
/**
* Constructs with the default PCM module number (CAN ID).
*/
CTREPCMSim();
/**
* Constructs from a PCM module number (CAN ID).
*
* @param module module number
*/
explicit CTREPCMSim(int module);
explicit CTREPCMSim(const PneumaticsBase& pneumatics);
~CTREPCMSim() override = default;
[[nodiscard]]
std::unique_ptr<CallbackStore> RegisterInitializedCallback(
NotifyCallback callback, bool initialNotify) override;
bool GetInitialized() const override;
void SetInitialized(bool initialized) override;
[[nodiscard]]
std::unique_ptr<CallbackStore> RegisterSolenoidOutputCallback(
int channel, NotifyCallback callback, bool initialNotify) override;
bool GetSolenoidOutput(int channel) const override;
void SetSolenoidOutput(int channel, bool solenoidOutput) override;
[[nodiscard]]
std::unique_ptr<CallbackStore> RegisterCompressorOnCallback(
NotifyCallback callback, bool initialNotify) override;
bool GetCompressorOn() const override;
void SetCompressorOn(bool compressorOn) override;
/**
* Register a callback to be run whenever the closed loop state changes.
*
* @param callback the callback
* @param initialNotify whether the callback should be called with the
* initial value
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
std::unique_ptr<CallbackStore> RegisterClosedLoopEnabledCallback(
NotifyCallback callback, bool initialNotify);
/**
* Check whether the closed loop compressor control is active.
*
* @return true if active
*/
bool GetClosedLoopEnabled() const;
/**
* Turn on/off the closed loop control of the compressor.
*
* @param closedLoopEnabled whether the control loop is active
*/
void SetClosedLoopEnabled(bool closedLoopEnabled);
/**
* Register a callback to be run whenever the pressure switch value changes.
*
* @param callback the callback
* @param initialNotify whether the callback should be called with the
* initial value
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
std::unique_ptr<CallbackStore> RegisterPressureSwitchCallback(
NotifyCallback callback, bool initialNotify) override;
/**
* Check the value of the pressure switch.
*
* @return the pressure switch value
*/
bool GetPressureSwitch() const override;
/**
* Set the value of the pressure switch.
*
* @param pressureSwitch the new value
*/
void SetPressureSwitch(bool pressureSwitch) override;
/**
* Register a callback to be run whenever the compressor current changes.
*
* @param callback the callback
* @param initialNotify whether to call the callback with the initial state
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
std::unique_ptr<CallbackStore> RegisterCompressorCurrentCallback(
NotifyCallback callback, bool initialNotify) override;
/**
* Read the compressor current.
*
* @return the current of the compressor connected to this module
*/
double GetCompressorCurrent() const override;
/**
* Set the compressor current.
*
* @param compressorCurrent the new compressor current
*/
void SetCompressorCurrent(double compressorCurrent) override;
uint8_t GetAllSolenoidOutputs() const override;
void SetAllSolenoidOutputs(uint8_t outputs) override;
void ResetData() override;
};
} // namespace frc::sim

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.
#pragma once
#include <functional>
#include <string_view>
#include <hal/Value.h>
namespace frc::sim {
using NotifyCallback = std::function<void(std::string_view, const HAL_Value*)>;
using ConstBufferCallback = std::function<void(
std::string_view, const unsigned char* buffer, unsigned int count)>;
using CancelCallbackFunc = void (*)(int32_t index, int32_t uid);
using CancelCallbackNoIndexFunc = void (*)(int32_t uid);
using CancelCallbackChannelFunc = void (*)(int32_t index, int32_t channel,
int32_t uid);
void CallbackStoreThunk(const char* name, void* param, const HAL_Value* value);
void ConstBufferCallbackStoreThunk(const char* name, void* param,
const unsigned char* buffer,
unsigned int count);
/**
* Manages simulation callbacks; each object is associated with a callback.
*/
class CallbackStore {
public:
CallbackStore(int32_t i, NotifyCallback cb, CancelCallbackNoIndexFunc ccf);
CallbackStore(int32_t i, int32_t u, NotifyCallback cb,
CancelCallbackFunc ccf);
CallbackStore(int32_t i, int32_t c, int32_t u, NotifyCallback cb,
CancelCallbackChannelFunc ccf);
CallbackStore(int32_t i, ConstBufferCallback cb,
CancelCallbackNoIndexFunc ccf);
CallbackStore(int32_t i, int32_t u, ConstBufferCallback cb,
CancelCallbackFunc ccf);
CallbackStore(int32_t i, int32_t c, int32_t u, ConstBufferCallback cb,
CancelCallbackChannelFunc ccf);
CallbackStore(const CallbackStore&) = delete;
CallbackStore& operator=(const CallbackStore&) = delete;
~CallbackStore();
void SetUid(int32_t uid);
friend void CallbackStoreThunk(const char* name, void* param,
const HAL_Value* value);
friend void ConstBufferCallbackStoreThunk(const char* name, void* param,
const unsigned char* buffer,
unsigned int count);
private:
int32_t index;
int32_t channel;
int32_t uid;
NotifyCallback callback;
ConstBufferCallback constBufferCallback;
union {
CancelCallbackFunc ccf;
CancelCallbackChannelFunc cccf;
CancelCallbackNoIndexFunc ccnif;
};
enum CancelType { Normal, Channel, NoIndex };
CancelType cancelType;
};
} // namespace frc::sim

View File

@@ -0,0 +1,131 @@
// 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.
#pragma once
#include <units/angle.h>
#include <units/angular_acceleration.h>
#include <units/angular_velocity.h>
#include <units/moment_of_inertia.h>
#include <units/torque.h>
#include "frc/simulation/LinearSystemSim.h"
#include "frc/system/LinearSystem.h"
#include "frc/system/plant/DCMotor.h"
namespace frc::sim {
/**
* Represents a simulated DC motor mechanism.
*/
class DCMotorSim : public LinearSystemSim<2, 1, 2> {
public:
/**
* Creates a simulated DC motor mechanism.
*
* @param plant The linear system representing the DC motor. This
* system can be created with LinearSystemId::DCMotorSystem(). If
* LinearSystemId::DCMotorSystem(kV, kA) is used, the distance unit must be
* radians.
* @param gearbox The type of and number of motors in the DC motor
* gearbox.
* @param measurementStdDevs The standard deviation of the measurement noise.
*/
DCMotorSim(const LinearSystem<2, 1, 2>& plant, const DCMotor& gearbox,
const std::array<double, 2>& measurementStdDevs = {0.0, 0.0});
using LinearSystemSim::SetState;
/**
* Sets the state of the DC motor.
*
* @param angularPosition The new position
* @param angularVelocity The new velocity
*/
void SetState(units::radian_t angularPosition,
units::radians_per_second_t angularVelocity);
/**
* Sets the DC motor's angular position.
*
* @param angularPosition The new position in radians.
*/
void SetAngle(units::radian_t angularPosition);
/**
* Sets the DC motor's angular velocity.
*
* @param angularVelocity The new velocity in radians per second.
*/
void SetAngularVelocity(units::radians_per_second_t angularVelocity);
/**
* Returns the DC motor position.
*
* @return The DC motor position.
*/
units::radian_t GetAngularPosition() const;
/**
* Returns the DC motor velocity.
*
* @return The DC motor velocity.
*/
units::radians_per_second_t GetAngularVelocity() const;
/**
* Returns the DC motor acceleration.
*
* @return The DC motor acceleration
*/
units::radians_per_second_squared_t GetAngularAcceleration() const;
/**
* Returns the DC motor torque.
*
* @return The DC motor torque
*/
units::newton_meter_t GetTorque() const;
/**
* Returns the DC motor current draw.
*
* @return The DC motor current draw.
*/
units::ampere_t GetCurrentDraw() const;
/**
* Gets the input voltage for the DC motor.
*
* @return The DC motor input voltage.
*/
units::volt_t GetInputVoltage() const;
/**
* Sets the input voltage for the DC motor.
*
* @param voltage The input voltage.
*/
void SetInputVoltage(units::volt_t voltage);
/**
* Returns the gearbox.
*/
const DCMotor& GetGearbox() const;
/**
* Returns the gearing;
*/
double GetGearing() const;
/**
* Returns the moment of inertia
*/
units::kilogram_square_meter_t GetJ() const;
private:
DCMotor m_gearbox;
double m_gearing;
units::kilogram_square_meter_t m_j;
};
} // namespace frc::sim

View File

@@ -0,0 +1,181 @@
// 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.
#pragma once
#include <memory>
#include "frc/simulation/CallbackStore.h"
namespace frc {
class DigitalInput;
class DigitalOutput;
namespace sim {
/**
* Class to control a simulated digital input or output.
*/
class DIOSim {
public:
/**
* Constructs from a DigitalInput object.
*
* @param input DigitalInput to simulate
*/
explicit DIOSim(const DigitalInput& input);
/**
* Constructs from a DigitalOutput object.
*
* @param output DigitalOutput to simulate
*/
explicit DIOSim(const DigitalOutput& output);
/**
* Constructs from an digital I/O channel number.
*
* @param channel Channel number
*/
explicit DIOSim(int channel);
/**
* Register a callback to be run when this DIO is initialized.
*
* @param callback the callback
* @param initialNotify whether to run the callback with the initial state
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
std::unique_ptr<CallbackStore> RegisterInitializedCallback(
NotifyCallback callback, bool initialNotify);
/**
* Check whether this DIO has been initialized.
*
* @return true if initialized
*/
bool GetInitialized() const;
/**
* Define whether this DIO has been initialized.
*
* @param initialized whether this object is initialized
*/
void SetInitialized(bool initialized);
/**
* Register a callback to be run whenever the DIO value changes.
*
* @param callback the callback
* @param initialNotify whether the callback should be called with the
* initial value
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
std::unique_ptr<CallbackStore> RegisterValueCallback(NotifyCallback callback,
bool initialNotify);
/**
* Read the value of the DIO port.
*
* @return the DIO value
*/
bool GetValue() const;
/**
* Change the DIO value.
*
* @param value the new value
*/
void SetValue(bool value);
/**
* Register a callback to be run whenever the pulse length changes.
*
* @param callback the callback
* @param initialNotify whether to call the callback with the initial state
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
std::unique_ptr<CallbackStore> RegisterPulseLengthCallback(
NotifyCallback callback, bool initialNotify);
/**
* Read the pulse length.
*
* @return the pulse length of this DIO port
*/
double GetPulseLength() const;
/**
* Change the pulse length of this DIO port.
*
* @param pulseLength the new pulse length
*/
void SetPulseLength(double pulseLength);
/**
* Register a callback to be run whenever this DIO changes to be an input.
*
* @param callback the callback
* @param initialNotify whether the callback should be called with the
* initial state
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
std::unique_ptr<CallbackStore> RegisterIsInputCallback(
NotifyCallback callback, bool initialNotify);
/**
* Check whether this DIO port is currently an Input.
*
* @return true if Input
*/
bool GetIsInput() const;
/**
* Define whether this DIO port is an Input.
*
* @param isInput whether this DIO should be an Input
*/
void SetIsInput(bool isInput);
/**
* Register a callback to be run whenever the filter index changes.
*
* @param callback the callback
* @param initialNotify whether the callback should be called with the
* initial value
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
std::unique_ptr<CallbackStore> RegisterFilterIndexCallback(
NotifyCallback callback, bool initialNotify);
/**
* Read the filter index.
*
* @return the filter index of this DIO port
*/
int GetFilterIndex() const;
/**
* Change the filter index of this DIO port.
*
* @param filterIndex the new filter index
*/
void SetFilterIndex(int filterIndex);
/**
* Reset all simulation data of this object.
*/
void ResetData();
private:
int m_index;
};
} // namespace sim
} // namespace frc

View File

@@ -0,0 +1,361 @@
// 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.
#pragma once
#include <frc/EigenCore.h>
#include <frc/kinematics/DifferentialDriveKinematics.h>
#include <frc/system/LinearSystem.h>
#include <frc/system/plant/DCMotor.h>
#include <units/length.h>
#include <units/moment_of_inertia.h>
#include <units/time.h>
#include <units/voltage.h>
namespace frc::sim {
class DifferentialDrivetrainSim {
public:
/**
* Creates a simulated differential drivetrain.
*
* @param plant The LinearSystem representing the robot's drivetrain. This
* system can be created with
* LinearSystemId::DrivetrainVelocitySystem() or
* LinearSystemId::IdentifyDrivetrainSystem().
* @param trackwidth The robot's trackwidth.
* @param driveMotor A DCMotor representing the left side of the drivetrain.
* @param gearingRatio The gearingRatio ratio of the left side, as output over
* input. This must be the same ratio as the ratio used to
* identify or create the plant.
* @param wheelRadius The radius of the wheels on the drivetrain, in meters.
* @param measurementStdDevs Standard deviations for measurements, in the form
* [x, y, heading, left velocity, right velocity,
* left distance, right distance]ᵀ. Can be omitted
* if no noise is desired. Gyro standard deviations
* of 0.0001 radians, velocity standard deviations
* of 0.05 m/s, and position measurement standard
* deviations of 0.005 meters are a reasonable
* starting point.
*/
DifferentialDrivetrainSim(
LinearSystem<2, 2, 2> plant, units::meter_t trackwidth,
DCMotor driveMotor, double gearingRatio, units::meter_t wheelRadius,
const std::array<double, 7>& measurementStdDevs = {});
/**
* Creates a simulated differential drivetrain.
*
* @param driveMotor A DCMotor representing the left side of the drivetrain.
* @param gearing The gearing on the drive between motor and wheel, as
* output over input. This must be the same ratio as the
* ratio used to identify or create the plant.
* @param J The moment of inertia of the drivetrain about its
* center.
* @param mass The mass of the drivebase.
* @param wheelRadius The radius of the wheels on the drivetrain.
* @param trackwidth The robot's trackwidth, or distance between left and
* right wheels.
* @param measurementStdDevs Standard deviations for measurements, in the form
* [x, y, heading, left velocity, right velocity,
* left distance, right distance]ᵀ. Can be omitted
* if no noise is desired. Gyro standard deviations
* of 0.0001 radians, velocity standard deviations
* of 0.05 m/s, and position measurement standard
* deviations of 0.005 meters are a reasonable
* starting point.
*/
DifferentialDrivetrainSim(
frc::DCMotor driveMotor, double gearing, units::kilogram_square_meter_t J,
units::kilogram_t mass, units::meter_t wheelRadius,
units::meter_t trackwidth,
const std::array<double, 7>& measurementStdDevs = {});
/**
* Clamp the input vector such that no element exceeds the battery voltage.
* If any does, the relative magnitudes of the input will be maintained.
*
* @param u The input vector.
* @return The normalized input.
*/
Eigen::Vector2d ClampInput(const Eigen::Vector2d& u);
/**
* Sets the applied voltage to the drivetrain. Note that positive voltage must
* make that side of the drivetrain travel forward (+X).
*
* @param leftVoltage The left voltage.
* @param rightVoltage The right voltage.
*/
void SetInputs(units::volt_t leftVoltage, units::volt_t rightVoltage);
/**
* Sets the gearing reduction on the drivetrain. This is commonly used for
* shifting drivetrains.
*
* @param newGearing The new gear ratio, as output over input.
*/
void SetGearing(double newGearing);
/**
* Updates the simulation.
*
* @param dt The time that's passed since the last Update(units::second_t)
* call.
*/
void Update(units::second_t dt);
/**
* Returns the current gearing reduction of the drivetrain, as output over
* input.
*/
double GetGearing() const;
/**
* Returns the direction the robot is pointing.
*
* Note that this angle is counterclockwise-positive, while most gyros are
* clockwise positive.
*/
Rotation2d GetHeading() const;
/**
* Returns the current pose.
*/
Pose2d GetPose() const;
/**
* Get the right encoder position in meters.
* @return The encoder position.
*/
units::meter_t GetRightPosition() const {
return units::meter_t{GetOutput(State::kRightPosition)};
}
/**
* Get the right encoder velocity in meters per second.
* @return The encoder velocity.
*/
units::meters_per_second_t GetRightVelocity() const {
return units::meters_per_second_t{GetOutput(State::kRightVelocity)};
}
/**
* Get the left encoder position in meters.
* @return The encoder position.
*/
units::meter_t GetLeftPosition() const {
return units::meter_t{GetOutput(State::kLeftPosition)};
}
/**
* Get the left encoder velocity in meters per second.
* @return The encoder velocity.
*/
units::meters_per_second_t GetLeftVelocity() const {
return units::meters_per_second_t{GetOutput(State::kLeftVelocity)};
}
/**
* Returns the currently drawn current for the right side.
*/
units::ampere_t GetRightCurrentDraw() const;
/**
* Returns the currently drawn current for the left side.
*/
units::ampere_t GetLeftCurrentDraw() const;
/**
* Returns the currently drawn current.
*/
units::ampere_t GetCurrentDraw() const;
/**
* Sets the system state.
*
* @param state The state.
*/
void SetState(const Vectord<7>& state);
/**
* Sets the system pose.
*
* @param pose The pose.
*/
void SetPose(const frc::Pose2d& pose);
/**
* The differential drive dynamics function.
*
* @param x The state.
* @param u The input.
* @return The state derivative with respect to time.
*/
Vectord<7> Dynamics(const Vectord<7>& x, const Eigen::Vector2d& u);
class State {
public:
static constexpr int kX = 0;
static constexpr int kY = 1;
static constexpr int kHeading = 2;
static constexpr int kLeftVelocity = 3;
static constexpr int kRightVelocity = 4;
static constexpr int kLeftPosition = 5;
static constexpr int kRightPosition = 6;
};
/**
* Represents a gearing option of the Toughbox mini.
* 12.75:1 -- 14:50 and 14:50
* 10.71:1 -- 14:50 and 16:48
* 8.45:1 -- 14:50 and 19:45
* 7.31:1 -- 14:50 and 21:43
* 5.95:1 -- 14:50 and 24:40
*/
class KitbotGearing {
public:
/// Gear ratio of 12.75:1.
static constexpr double k12p75 = 12.75;
/// Gear ratio of 10.71:1.
static constexpr double k10p71 = 10.71;
/// Gear ratio of 8.45:1.
static constexpr double k8p45 = 8.45;
/// Gear ratio of 7.31:1.
static constexpr double k7p31 = 7.31;
/// Gear ratio of 5.95:1.
static constexpr double k5p95 = 5.95;
};
/**
* Represents common motor layouts of the kit drivetrain.
*/
class KitbotMotor {
public:
/// One CIM motor per drive side.
static constexpr frc::DCMotor SingleCIMPerSide = frc::DCMotor::CIM(1);
/// Two CIM motors per drive side.
static constexpr frc::DCMotor DualCIMPerSide = frc::DCMotor::CIM(2);
/// One Mini CIM motor per drive side.
static constexpr frc::DCMotor SingleMiniCIMPerSide =
frc::DCMotor::MiniCIM(1);
/// Two Mini CIM motors per drive side.
static constexpr frc::DCMotor DualMiniCIMPerSide = frc::DCMotor::MiniCIM(2);
/// One Falcon 500 motor per drive side.
static constexpr frc::DCMotor SingleFalcon500PerSide =
frc::DCMotor::Falcon500(1);
/// Two Falcon 500 motors per drive side.
static constexpr frc::DCMotor DualFalcon500PerSide =
frc::DCMotor::Falcon500(2);
/// One NEO motor per drive side.
static constexpr frc::DCMotor SingleNEOPerSide = frc::DCMotor::NEO(1);
/// Two NEO motors per drive side.
static constexpr frc::DCMotor DualNEOPerSide = frc::DCMotor::NEO(2);
};
/**
* Represents common wheel sizes of the kit drivetrain.
*/
class KitbotWheelSize {
public:
/// Six inch diameter wheels.
static constexpr units::meter_t kSixInch = 6_in;
/// Eight inch diameter wheels.
static constexpr units::meter_t kEightInch = 8_in;
/// Ten inch diameter wheels.
static constexpr units::meter_t kTenInch = 10_in;
};
/**
* Create a sim for the standard FRC kitbot.
*
* @param motor The motors installed in the bot.
* @param gearing The gearing reduction used.
* @param wheelSize The wheel size.
* @param measurementStdDevs Standard deviations for measurements, in the form
* [x, y, heading, left velocity, right velocity, left distance, right
* distance]ᵀ. Can be omitted if no noise is desired. Gyro standard
* deviations of 0.0001 radians, velocity standard deviations of 0.05 m/s, and
* position measurement standard deviations of 0.005 meters are a reasonable
* starting point.
*/
static DifferentialDrivetrainSim CreateKitbotSim(
frc::DCMotor motor, double gearing, units::meter_t wheelSize,
const std::array<double, 7>& measurementStdDevs = {}) {
// MOI estimation -- note that I = mr² for point masses
units::kilogram_square_meter_t batteryMoi = 12.5_lb * 10_in * 10_in;
units::kilogram_square_meter_t gearboxMoi = (2.8_lb + 2.0_lb) *
2 // CIM plus toughbox per side
* (26_in / 2) * (26_in / 2);
return DifferentialDrivetrainSim{
motor, gearing, batteryMoi + gearboxMoi, 60_lb,
wheelSize / 2.0, 26_in, measurementStdDevs};
}
/**
* Create a sim for the standard FRC kitbot.
*
* @param motor The motors installed in the bot.
* @param gearing The gearing reduction used.
* @param wheelSize The wheel size.
* @param J The moment of inertia of the drivebase. This can be
* calculated using SysId.
* @param measurementStdDevs Standard deviations for measurements, in the form
* [x, y, heading, left velocity, right velocity, left distance, right
* distance]ᵀ. Can be omitted if no noise is desired. Gyro standard
* deviations of 0.0001 radians, velocity standard deviations of 0.05 m/s, and
* position measurement standard deviations of 0.005 meters are a reasonable
* starting point.
*/
static DifferentialDrivetrainSim CreateKitbotSim(
frc::DCMotor motor, double gearing, units::meter_t wheelSize,
units::kilogram_square_meter_t J,
const std::array<double, 7>& measurementStdDevs = {}) {
return DifferentialDrivetrainSim{
motor, gearing, J, 60_lb, wheelSize / 2.0, 26_in, measurementStdDevs};
}
private:
/**
* Returns an element of the state vector.
*
* @param output The row of the output vector.
*/
double GetOutput(int output) const;
/**
* Returns the current output vector y.
*/
Vectord<7> GetOutput() const;
/**
* Returns an element of the state vector. Note that this will not include
* noise!
*
* @param output The row of the output vector.
*/
double GetState(int state) const;
/**
* Returns the current state vector x. Note that this will not include noise!
*/
Vectord<7> GetState() const;
LinearSystem<2, 2, 2> m_plant;
units::meter_t m_rb;
units::meter_t m_wheelRadius;
DCMotor m_motor;
double m_originalGearing;
double m_currentGearing;
Vectord<7> m_x;
Eigen::Vector2d m_u;
Vectord<7> m_y;
std::array<double, 7> m_measurementStdDevs;
};
} // namespace frc::sim

View File

@@ -0,0 +1,136 @@
// 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.
#pragma once
#include <memory>
#include "frc/simulation/CallbackStore.h"
namespace frc {
class DigitalOutput;
namespace sim {
/**
* Class to control a simulated digital PWM output.
*
* This is for duty cycle PWM outputs on a DigitalOutput, not for the servo
* style PWM outputs on a PWM channel.
*/
class DigitalPWMSim {
public:
/**
* Constructs from a DigitalOutput object.
*
* @param digitalOutput DigitalOutput to simulate
*/
explicit DigitalPWMSim(const DigitalOutput& digitalOutput);
/**
* Creates an DigitalPWMSim for a digital I/O channel.
*
* @param channel DIO channel
* @return Simulated object
* @throws std::out_of_range if no Digital PWM is configured for that channel
*/
static DigitalPWMSim CreateForChannel(int channel);
/**
* Creates an DigitalPWMSim for a simulated index.
* The index is incremented for each simulated DigitalPWM.
*
* @param index simulator index
* @return Simulated object
*/
static DigitalPWMSim CreateForIndex(int index);
/**
* Register a callback to be run when this PWM output is initialized.
*
* @param callback the callback
* @param initialNotify whether to run the callback with the initial state
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
std::unique_ptr<CallbackStore> RegisterInitializedCallback(
NotifyCallback callback, bool initialNotify);
/**
* Check whether this PWM output has been initialized.
*
* @return true if initialized
*/
bool GetInitialized() const;
/**
* Define whether this PWM output has been initialized.
*
* @param initialized whether this object is initialized
*/
void SetInitialized(bool initialized);
/**
* Register a callback to be run whenever the duty cycle value changes.
*
* @param callback the callback
* @param initialNotify whether to call the callback with the initial state
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
std::unique_ptr<CallbackStore> RegisterDutyCycleCallback(
NotifyCallback callback, bool initialNotify);
/**
* Read the duty cycle value.
*
* @return the duty cycle value of this PWM output
*/
double GetDutyCycle() const;
/**
* Set the duty cycle value of this PWM output.
*
* @param dutyCycle the new value
*/
void SetDutyCycle(double dutyCycle);
/**
* Register a callback to be run whenever the pin changes.
*
* @param callback the callback
* @param initialNotify whether to call the callback with the initial state
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
std::unique_ptr<CallbackStore> RegisterPinCallback(NotifyCallback callback,
bool initialNotify);
/**
* Check the pin number.
*
* @return the pin number
*/
int GetPin() const;
/**
* Change the pin number.
*
* @param pin the new pin number
*/
void SetPin(int pin);
/**
* Reset all simulation data.
*/
void ResetData();
private:
explicit DigitalPWMSim(int index) : m_index{index} {}
int m_index;
};
} // namespace sim
} // namespace frc

View File

@@ -0,0 +1,33 @@
// 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.
#pragma once
#include <memory>
#include "frc/DoubleSolenoid.h"
#include "frc/PneumaticsModuleType.h"
#include "frc/simulation/PneumaticsBaseSim.h"
namespace frc::sim {
class DoubleSolenoidSim {
public:
DoubleSolenoidSim(std::shared_ptr<PneumaticsBaseSim> moduleSim, int fwd,
int rev);
DoubleSolenoidSim(int module, PneumaticsModuleType type, int fwd, int rev);
DoubleSolenoidSim(PneumaticsModuleType type, int fwd, int rev);
DoubleSolenoid::Value Get() const;
void Set(DoubleSolenoid::Value output);
std::shared_ptr<PneumaticsBaseSim> GetModuleSim() const;
private:
std::shared_ptr<PneumaticsBaseSim> m_module;
int m_fwd;
int m_rev;
};
} // namespace frc::sim

View File

@@ -0,0 +1,400 @@
// 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.
#pragma once
#include <memory>
#include <hal/DriverStationTypes.h>
#include "frc/DriverStation.h"
#include "frc/simulation/CallbackStore.h"
namespace frc::sim {
/**
* Class to control a simulated driver station.
*/
class DriverStationSim {
public:
/**
* Register a callback on whether the DS is enabled.
*
* @param callback the callback that will be called whenever the enabled
* state is changed
* @param initialNotify if true, the callback will be run on the initial value
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
static std::unique_ptr<CallbackStore> RegisterEnabledCallback(
NotifyCallback callback, bool initialNotify);
/**
* Check if the DS is enabled.
*
* @return true if enabled
*/
static bool GetEnabled();
/**
* Change whether the DS is enabled.
*
* @param enabled the new value
*/
static void SetEnabled(bool enabled);
/**
* Register a callback on whether the DS is in autonomous mode.
*
* @param callback the callback that will be called on autonomous mode
* entrance/exit
* @param initialNotify if true, the callback will be run on the initial value
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
static std::unique_ptr<CallbackStore> RegisterAutonomousCallback(
NotifyCallback callback, bool initialNotify);
/**
* Check if the DS is in autonomous.
*
* @return true if autonomous
*/
static bool GetAutonomous();
/**
* Change whether the DS is in autonomous.
*
* @param autonomous the new value
*/
static void SetAutonomous(bool autonomous);
/**
* Register a callback on whether the DS is in test mode.
*
* @param callback the callback that will be called whenever the test mode
* is entered or left
* @param initialNotify if true, the callback will be run on the initial value
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
static std::unique_ptr<CallbackStore> RegisterTestCallback(
NotifyCallback callback, bool initialNotify);
/**
* Check if the DS is in test.
*
* @return true if test
*/
static bool GetTest();
/**
* Change whether the DS is in test.
*
* @param test the new value
*/
static void SetTest(bool test);
/**
* Register a callback on the eStop state.
*
* @param callback the callback that will be called whenever the eStop state
* changes
* @param initialNotify if true, the callback will be run on the initial value
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
static std::unique_ptr<CallbackStore> RegisterEStopCallback(
NotifyCallback callback, bool initialNotify);
/**
* Check if eStop has been activated.
*
* @return true if eStopped
*/
static bool GetEStop();
/**
* Set whether eStop is active.
*
* @param eStop true to activate
*/
static void SetEStop(bool eStop);
/**
* Register a callback on whether the FMS is connected.
*
* @param callback the callback that will be called whenever the FMS
* connection changes
* @param initialNotify if true, the callback will be run on the initial value
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
static std::unique_ptr<CallbackStore> RegisterFmsAttachedCallback(
NotifyCallback callback, bool initialNotify);
/**
* Check if the FMS is connected.
*
* @return true if FMS is connected
*/
static bool GetFmsAttached();
/**
* Change whether the FMS is connected.
*
* @param fmsAttached the new value
*/
static void SetFmsAttached(bool fmsAttached);
/**
* Register a callback on whether the DS is connected.
*
* @param callback the callback that will be called whenever the DS
* connection changes
* @param initialNotify if true, the callback will be run on the initial value
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
static std::unique_ptr<CallbackStore> RegisterDsAttachedCallback(
NotifyCallback callback, bool initialNotify);
/**
* Check if the DS is attached.
*
* @return true if attached
*/
static bool GetDsAttached();
/**
* Change whether the DS is attached.
*
* @param dsAttached the new value
*/
static void SetDsAttached(bool dsAttached);
/**
* Register a callback on the alliance station ID.
*
* @param callback the callback that will be called whenever the alliance
* station changes
* @param initialNotify if true, the callback will be run on the initial value
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
static std::unique_ptr<CallbackStore> RegisterAllianceStationIdCallback(
NotifyCallback callback, bool initialNotify);
/**
* Get the alliance station ID (color + number).
*
* @return the alliance station color and number
*/
static HAL_AllianceStationID GetAllianceStationId();
/**
* Change the alliance station.
*
* @param allianceStationId the new alliance station
*/
static void SetAllianceStationId(HAL_AllianceStationID allianceStationId);
/**
* Register a callback on match time.
*
* @param callback the callback that will be called whenever match time
* changes
* @param initialNotify if true, the callback will be run on the initial value
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
static std::unique_ptr<CallbackStore> RegisterMatchTimeCallback(
NotifyCallback callback, bool initialNotify);
/**
* Get the current value of the match timer.
*
* @return the current match time
*/
static double GetMatchTime();
/**
* Sets the match timer.
*
* @param matchTime the new match time
*/
static void SetMatchTime(double matchTime);
/**
* Updates DriverStation data so that new values are visible to the user
* program.
*/
static void NotifyNewData();
/**
* Sets suppression of DriverStation::ReportError and ReportWarning messages.
*
* @param shouldSend If false then messages will be suppressed.
*/
static void SetSendError(bool shouldSend);
/**
* Sets suppression of DriverStation::SendConsoleLine messages.
*
* @param shouldSend If false then messages will be suppressed.
*/
static void SetSendConsoleLine(bool shouldSend);
/**
* Gets the joystick outputs.
*
* @param stick The joystick number
* @return The joystick outputs
*/
static int64_t GetJoystickOutputs(int stick);
/**
* Gets the joystick rumble.
*
* @param stick The joystick number
* @param rumbleNum Rumble to get (0=left, 1=right)
* @return The joystick rumble value
*/
static int GetJoystickRumble(int stick, int rumbleNum);
/**
* Sets the state of one joystick button. %Button indexes begin at 0.
*
* @param stick The joystick number
* @param button The button index, beginning at 0
* @param state The state of the joystick button
*/
static void SetJoystickButton(int stick, int button, bool state);
/**
* Gets the value of the axis on a joystick.
*
* @param stick The joystick number
* @param axis The analog axis number
* @param value The value of the axis on the joystick
*/
static void SetJoystickAxis(int stick, int axis, double value);
/**
* Gets the state of a POV on a joystick.
*
* @param stick The joystick number
* @param pov The POV number
* @param value the angle of the POV
*/
static void SetJoystickPOV(int stick, int pov,
DriverStation::POVDirection value);
/**
* Sets the number of axes for a joystick.
*
* @param stick The joystick number
* @param maximumIndex The number of axes on the indicated joystick
*/
static void SetJoystickAxesMaximumIndex(int stick, int maximumIndex);
/**
* Sets the number of axes for a joystick.
*
* @param stick The joystick number
* @param available The number of axes on the indicated joystick
*/
static void SetJoystickAxesAvailable(int stick, int available);
/**
* Sets the number of POVs for a joystick.
*
* @param stick The joystick number
* @param maximumIndex The number of POVs on the indicated joystick
*/
static void SetJoystickPOVsMaximumIndex(int stick, int maximumIndex);
/**
* Sets the number of POVs for a joystick.
*
* @param stick The joystick number
* @param available The number of POVs on the indicated joystick
*/
static void SetJoystickPOVsAvailable(int stick, int available);
/**
* Sets the number of buttons for a joystick.
*
* @param stick The joystick number
* @param count The number of buttons on the indicated joystick
*/
static void SetJoystickButtonsMaximumIndex(int stick, int count);
static void SetJoystickButtonsAvailable(int stick, uint64_t available);
/**
* Sets the value of isGamepad for a joystick.
*
* @param stick The joystick number
* @param isGamepad The value of isGamepad
*/
static void SetJoystickIsGamepad(int stick, bool isGamepad);
/**
* Sets the value of type for a joystick.
*
* @param stick The joystick number
* @param type The value of type
*/
static void SetJoystickType(int stick, int type);
/**
* Sets the name of a joystick.
*
* @param stick The joystick number
* @param name The value of name
*/
static void SetJoystickName(int stick, std::string_view name);
/**
* Sets the game specific message.
*
* @param message the game specific message
*/
static void SetGameSpecificMessage(std::string_view message);
/**
* Sets the event name.
*
* @param name the event name
*/
static void SetEventName(std::string_view name);
/**
* Sets the match type.
*
* @param type the match type
*/
static void SetMatchType(DriverStation::MatchType type);
/**
* Sets the match number.
*
* @param matchNumber the match number
*/
static void SetMatchNumber(int matchNumber);
/**
* Sets the replay number.
*
* @param replayNumber the replay number
*/
static void SetReplayNumber(int replayNumber);
/**
* Reset all simulation data for the Driver Station.
*/
static void ResetData();
};
} // namespace frc::sim

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.
#pragma once
#include <hal/SimDevice.h>
#include <units/angle.h>
namespace frc {
class DutyCycleEncoder;
namespace sim {
/**
* Class to control a simulated duty cycle encoder.
*/
class DutyCycleEncoderSim {
public:
/**
* Constructs from a DutyCycleEncoder object.
*
* @param encoder DutyCycleEncoder to simulate
*/
explicit DutyCycleEncoderSim(const DutyCycleEncoder& encoder);
/**
* Constructs from a digital input channel.
*
* @param channel digital input channel
*/
explicit DutyCycleEncoderSim(int channel);
/**
* Get the position.
*
* @return The position.
*/
double Get();
/**
* Set the position.
*
* @param value The position.
*/
void Set(double value);
/**
* Get if the encoder is connected.
*
* @return true if the encoder is connected.
*/
bool IsConnected();
/**
* Set if the encoder is connected.
*
* @param isConnected Whether or not the sensor is connected.
*/
void SetConnected(bool isConnected);
private:
hal::SimDouble m_simPosition;
hal::SimBoolean m_simIsConnected;
};
} // namespace sim
} // namespace frc

View File

@@ -0,0 +1,125 @@
// 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.
#pragma once
#include <memory>
#include <units/frequency.h>
#include "frc/simulation/CallbackStore.h"
namespace frc {
class DutyCycle;
namespace sim {
/**
* Class to control a simulated duty cycle digital input.
*/
class DutyCycleSim {
public:
/**
* Constructs from a DutyCycle object.
*
* @param dutyCycle DutyCycle to simulate
*/
explicit DutyCycleSim(const DutyCycle& dutyCycle);
/**
* Creates a DutyCycleSim for a SmartIO channel.
*
* @param channel SmartIO channel
* @return Simulated object
*/
static DutyCycleSim CreateForChannel(int channel);
/**
* Register a callback to be run when this duty cycle input is initialized.
*
* @param callback the callback
* @param initialNotify whether to run the callback with the initial state
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
std::unique_ptr<CallbackStore> RegisterInitializedCallback(
NotifyCallback callback, bool initialNotify);
/**
* Check whether this duty cycle input has been initialized.
*
* @return true if initialized
*/
bool GetInitialized() const;
/**
* Define whether this duty cycle input has been initialized.
*
* @param initialized whether this object is initialized
*/
void SetInitialized(bool initialized);
/**
* Register a callback to be run whenever the frequency changes.
*
* @param callback the callback
* @param initialNotify whether to call the callback with the initial state
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
std::unique_ptr<CallbackStore> RegisterFrequencyCallback(
NotifyCallback callback, bool initialNotify);
/**
* Measure the frequency.
*
* @return the duty cycle frequency
*/
units::hertz_t GetFrequency() const;
/**
* Change the duty cycle frequency.
*
* @param frequency the new frequency
*/
void SetFrequency(units::hertz_t frequency);
/**
* Register a callback to be run whenever the output changes.
*
* @param callback the callback
* @param initialNotify whether to call the callback with the initial state
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
std::unique_ptr<CallbackStore> RegisterOutputCallback(NotifyCallback callback,
bool initialNotify);
/**
* Measure the output from this duty cycle port.
*
* @return the output value
*/
double GetOutput() const;
/**
* Change the duty cycle output.
*
* @param output the new output value
*/
void SetOutput(double output);
/**
* Reset all simulation data for the duty cycle output.
*/
void ResetData();
private:
explicit DutyCycleSim(int index) : m_index{index} {}
int m_index;
};
} // namespace sim
} // namespace frc

View File

@@ -0,0 +1,179 @@
// 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.
#pragma once
#include <array>
#include <units/length.h>
#include <units/mass.h>
#include <units/velocity.h>
#include "frc/simulation/LinearSystemSim.h"
#include "frc/system/plant/DCMotor.h"
namespace frc::sim {
/**
* Represents a simulated elevator mechanism.
*/
class ElevatorSim : public LinearSystemSim<2, 1, 2> {
public:
template <typename Distance>
using Velocity_t = units::unit_t<
units::compound_unit<Distance, units::inverse<units::seconds>>>;
template <typename Distance>
using Acceleration_t = units::unit_t<units::compound_unit<
units::compound_unit<Distance, units::inverse<units::seconds>>,
units::inverse<units::seconds>>>;
/**
* Constructs a simulated elevator mechanism.
*
* @param plant The linear system that represents the elevator.
* This system can be created with
* LinearSystemId::ElevatorSystem().
* @param gearbox The type of and number of motors in your
* elevator gearbox.
* @param minHeight The minimum allowed height of the elevator.
* @param maxHeight The maximum allowed height of the elevator.
* @param simulateGravity Whether gravity should be simulated or not.
* @param startingHeight The starting height of the elevator.
* @param measurementStdDevs The standard deviation of the measurements.
*/
ElevatorSim(const LinearSystem<2, 1, 2>& plant, const DCMotor& gearbox,
units::meter_t minHeight, units::meter_t maxHeight,
bool simulateGravity, units::meter_t startingHeight,
const std::array<double, 2>& measurementStdDevs = {0.0, 0.0});
/**
* Constructs a simulated elevator mechanism.
*
* @param gearbox The type of and number of motors in your
* elevator gearbox.
* @param gearing The gearing of the elevator (numbers greater
* than 1 represent reductions).
* @param carriageMass The mass of the elevator carriage.
* @param drumRadius The radius of the drum that your cable is
* wrapped around.
* @param minHeight The minimum allowed height of the elevator.
* @param maxHeight The maximum allowed height of the elevator.
* @param simulateGravity Whether gravity should be simulated or not.
* @param startingHeight The starting height of the elevator.
* @param measurementStdDevs The standard deviation of the measurements.
*/
ElevatorSim(const DCMotor& gearbox, double gearing,
units::kilogram_t carriageMass, units::meter_t drumRadius,
units::meter_t minHeight, units::meter_t maxHeight,
bool simulateGravity, units::meter_t startingHeight,
const std::array<double, 2>& measurementStdDevs = {0.0, 0.0});
/**
* Constructs a simulated elevator mechanism.
*
* @param kV The velocity gain.
* @param kA The acceleration gain.
* @param gearbox The type of and number of motors in your
* elevator gearbox.
* @param minHeight The minimum allowed height of the elevator.
* @param maxHeight The maximum allowed height of the elevator.
* @param simulateGravity Whether gravity should be simulated or not.
* @param startingHeight The starting height of the elevator.
* @param measurementStdDevs The standard deviation of the measurements.
*/
template <typename Distance>
requires std::same_as<units::meter, Distance> ||
std::same_as<units::radian, Distance>
ElevatorSim(decltype(1_V / Velocity_t<Distance>(1)) kV,
decltype(1_V / Acceleration_t<Distance>(1)) kA,
const DCMotor& gearbox, units::meter_t minHeight,
units::meter_t maxHeight, bool simulateGravity,
units::meter_t startingHeight,
const std::array<double, 2>& measurementStdDevs = {0.0, 0.0});
using LinearSystemSim::SetState;
/**
* Sets the elevator's state. The new position will be limited between the
* minimum and maximum allowed heights.
* @param position The new position
* @param velocity The new velocity
*/
void SetState(units::meter_t position, units::meters_per_second_t velocity);
/**
* Returns whether the elevator would hit the lower limit.
*
* @param elevatorHeight The elevator height.
* @return Whether the elevator would hit the lower limit.
*/
bool WouldHitLowerLimit(units::meter_t elevatorHeight) const;
/**
* Returns whether the elevator would hit the upper limit.
*
* @param elevatorHeight The elevator height.
* @return Whether the elevator would hit the upper limit.
*/
bool WouldHitUpperLimit(units::meter_t elevatorHeight) const;
/**
* Returns whether the elevator has hit the lower limit.
*
* @return Whether the elevator has hit the lower limit.
*/
bool HasHitLowerLimit() const;
/**
* Returns whether the elevator has hit the upper limit.
*
* @return Whether the elevator has hit the upper limit.
*/
bool HasHitUpperLimit() const;
/**
* Returns the position of the elevator.
*
* @return The position of the elevator.
*/
units::meter_t GetPosition() const;
/**
* Returns the velocity of the elevator.
*
* @return The velocity of the elevator.
*/
units::meters_per_second_t GetVelocity() const;
/**
* Returns the elevator current draw.
*
* @return The elevator current draw.
*/
units::ampere_t GetCurrentDraw() const;
/**
* Sets the input voltage for the elevator.
*
* @param voltage The input voltage.
*/
void SetInputVoltage(units::volt_t voltage);
protected:
/**
* Updates the state estimate of the elevator.
*
* @param currentXhat The current state estimate.
* @param u The system inputs (voltage).
* @param dt The time difference between controller updates.
*/
Vectord<2> UpdateX(const Vectord<2>& currentXhat, const Vectord<1>& u,
units::second_t dt) override;
private:
DCMotor m_gearbox;
units::meter_t m_minHeight;
units::meter_t m_maxHeight;
bool m_simulateGravity;
};
} // namespace frc::sim

View File

@@ -0,0 +1,320 @@
// 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.
#pragma once
#include <memory>
#include "frc/simulation/CallbackStore.h"
namespace frc {
class Encoder;
namespace sim {
/**
* Class to control a simulated encoder.
*/
class EncoderSim {
public:
/**
* Constructs from an Encoder object.
*
* @param encoder Encoder to simulate
*/
explicit EncoderSim(const Encoder& encoder);
/**
* Creates an EncoderSim for a digital input channel. Encoders take two
* channels, so either one may be specified.
*
* @param channel digital input channel
* @return Simulated object
* @throws NoSuchElementException if no Encoder is configured for that channel
*/
static EncoderSim CreateForChannel(int channel);
/**
* Creates an EncoderSim for a simulated index.
* The index is incremented for each simulated Encoder.
*
* @param index simulator index
* @return Simulated object
*/
static EncoderSim CreateForIndex(int index);
/**
* Register a callback on the Initialized property of the encoder.
*
* @param callback the callback that will be called whenever the Initialized
* property is changed
* @param initialNotify if true, the callback will be run on the initial value
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
std::unique_ptr<CallbackStore> RegisterInitializedCallback(
NotifyCallback callback, bool initialNotify);
/**
* Read the Initialized value of the encoder.
*
* @return true if initialized
*/
bool GetInitialized() const;
/**
* Change the Initialized value of the encoder.
*
* @param initialized the new value
*/
void SetInitialized(bool initialized);
/**
* Register a callback on the count property of the encoder.
*
* @param callback the callback that will be called whenever the count
* property is changed
* @param initialNotify if true, the callback will be run on the initial value
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
std::unique_ptr<CallbackStore> RegisterCountCallback(NotifyCallback callback,
bool initialNotify);
/**
* Read the count of the encoder.
*
* @return the count
*/
int GetCount() const;
/**
* Change the count of the encoder.
*
* @param count the new count
*/
void SetCount(int count);
/**
* Register a callback on the period of the encoder.
*
* @param callback the callback that will be called whenever the period is
* changed
* @param initialNotify if true, the callback will be run on the initial value
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
std::unique_ptr<CallbackStore> RegisterPeriodCallback(NotifyCallback callback,
bool initialNotify);
/**
* Read the period of the encoder.
*
* @return the encoder period
*/
double GetPeriod() const;
/**
* Change the encoder period.
*
* @param period the new period
*/
void SetPeriod(double period);
/**
* Register a callback to be called whenever the encoder is reset.
*
* @param callback the callback
* @param initialNotify whether to run the callback on the initial value
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
std::unique_ptr<CallbackStore> RegisterResetCallback(NotifyCallback callback,
bool initialNotify);
/**
* Check if the encoder has been reset.
*
* @return true if reset
*/
bool GetReset() const;
/**
* Change the reset property of the encoder.
*
* @param reset the new value
*/
void SetReset(bool reset);
/**
* Register a callback to be run whenever the max period of the encoder is
* changed.
*
* @param callback the callback
* @param initialNotify whether to run the callback on the initial value
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
std::unique_ptr<CallbackStore> RegisterMaxPeriodCallback(
NotifyCallback callback, bool initialNotify);
/**
* Get the max period of the encoder.
*
* @return the max period of the encoder
*/
double GetMaxPeriod() const;
/**
* Change the max period of the encoder.
*
* @param maxPeriod the new value
*/
void SetMaxPeriod(double maxPeriod);
/**
* Register a callback on the direction of the encoder.
*
* @param callback the callback that will be called whenever the direction
* is changed
* @param initialNotify if true, the callback will be run on the initial value
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
std::unique_ptr<CallbackStore> RegisterDirectionCallback(
NotifyCallback callback, bool initialNotify);
/**
* Get the direction of the encoder.
*
* @return the direction of the encoder
*/
bool GetDirection() const;
/**
* Set the direction of the encoder.
*
* @param direction the new direction
*/
void SetDirection(bool direction);
/**
* Register a callback on the reverse direction.
*
* @param callback the callback that will be called whenever the reverse
* direction is changed
* @param initialNotify if true, the callback will be run on the initial value
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
std::unique_ptr<CallbackStore> RegisterReverseDirectionCallback(
NotifyCallback callback, bool initialNotify);
/**
* Get the reverse direction of the encoder.
*
* @return the reverse direction of the encoder
*/
bool GetReverseDirection() const;
/**
* Set the reverse direction.
*
* @param reverseDirection the new value
*/
void SetReverseDirection(bool reverseDirection);
/**
* Register a callback on the samples-to-average value of this encoder.
*
* @param callback the callback that will be called whenever the
* samples-to-average is changed
* @param initialNotify if true, the callback will be run on the initial value
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
std::unique_ptr<CallbackStore> RegisterSamplesToAverageCallback(
NotifyCallback callback, bool initialNotify);
/**
* Get the samples-to-average value.
*
* @return the samples-to-average value
*/
int GetSamplesToAverage() const;
/**
* Set the samples-to-average value.
*
* @param samplesToAverage the new value
*/
void SetSamplesToAverage(int samplesToAverage);
/**
* Register a callback on the distance per pulse value of this encoder.
*
* @param callback the callback that will be called whenever the
* distance per pulse is changed
* @param initialNotify if true, the callback will be run on the initial value
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
std::unique_ptr<CallbackStore> RegisterDistancePerPulseCallback(
NotifyCallback callback, bool initialNotify);
/**
* Read the distance per pulse of the encoder.
*
* @return the encoder distance per pulse
*/
double GetDistancePerPulse() const;
/**
* Change the encoder distance per pulse.
*
* @param distancePerPulse the new distance per pulse
*/
void SetDistancePerPulse(double distancePerPulse);
/**
* Resets all simulation data for this encoder.
*/
void ResetData();
/**
* Change the encoder distance.
*
* @param distance the new distance
*/
void SetDistance(double distance);
/**
* Read the distance of the encoder.
*
* @return the encoder distance
*/
double GetDistance() const;
/**
* Change the rate of the encoder.
*
* @param rate the new rate
*/
void SetRate(double rate);
/**
* Get the rate of the encoder.
*
* @return the rate of change
*/
double GetRate() const;
private:
explicit EncoderSim(int index) : m_index{index} {}
int m_index;
};
} // namespace sim
} // namespace frc

View File

@@ -0,0 +1,107 @@
// 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.
#pragma once
#include <units/angular_acceleration.h>
#include <units/angular_velocity.h>
#include <units/moment_of_inertia.h>
#include <units/torque.h>
#include "frc/simulation/LinearSystemSim.h"
#include "frc/system/LinearSystem.h"
#include "frc/system/plant/DCMotor.h"
namespace frc::sim {
/**
* Represents a simulated flywheel mechanism.
*/
class FlywheelSim : public LinearSystemSim<1, 1, 1> {
public:
/**
* Creates a simulated flywheel mechanism.
*
* @param plant The linear system representing the flywheel. This
* system can be created with
* LinearSystemId::FlywheelSystem() or
* LinearSystemId::IdentifyVelocitySystem().
* @param gearbox The type of and number of motors in the flywheel
* gearbox.
* @param measurementStdDevs The standard deviation of the measurement noise.
*/
FlywheelSim(const LinearSystem<1, 1, 1>& plant, const DCMotor& gearbox,
const std::array<double, 1>& measurementStdDevs = {0.0});
using LinearSystemSim::SetState;
/**
* Sets the flywheel's angular velocity.
*
* @param velocity The new velocity
*/
void SetVelocity(units::radians_per_second_t velocity);
/**
* Returns the flywheel's velocity.
*
* @return The flywheel's velocity.
*/
units::radians_per_second_t GetAngularVelocity() const;
/**
* Returns the flywheel's acceleration.
*
* @return The flywheel's acceleration
*/
units::radians_per_second_squared_t GetAngularAcceleration() const;
/**
* Returns the flywheel's torque.
*
* @return The flywheel's torque
*/
units::newton_meter_t GetTorque() const;
/**
* Returns the flywheel's current draw.
*
* @return The flywheel's current draw.
*/
units::ampere_t GetCurrentDraw() const;
/**
* Gets the input voltage for the flywheel.
*
* @return The flywheel input voltage.
*/
units::volt_t GetInputVoltage() const;
/**
* Sets the input voltage for the flywheel.
*
* @param voltage The input voltage.
*/
void SetInputVoltage(units::volt_t voltage);
/**
* Returns the gearbox.
*/
DCMotor Gearbox() const { return m_gearbox; }
/**
* Returns the gearing;
*/
double Gearing() const { return m_gearing; }
/**
* Returns the moment of inertia
*/
units::kilogram_square_meter_t J() const { return m_j; }
private:
DCMotor m_gearbox;
double m_gearing;
units::kilogram_square_meter_t m_j;
};
} // namespace frc::sim

View File

@@ -0,0 +1,260 @@
// 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.
#pragma once
#include "frc/simulation/GenericHIDSim.h"
namespace frc {
class Gamepad;
namespace sim {
/**
* Class to control a simulated Gamepad controller.
*/
class GamepadSim : public GenericHIDSim {
public:
/**
* Constructs from a Gamepad object.
*
* @param joystick controller to simulate
*/
explicit GamepadSim(const Gamepad& joystick);
/**
* Constructs from a joystick port number.
*
* @param port port number
*/
explicit GamepadSim(int port);
/**
* Change the left X value of the controller's joystick.
*
* @param value the new value
*/
void SetLeftX(double value);
/**
* Change the left Y value of the controller's joystick.
*
* @param value the new value
*/
void SetLeftY(double value);
/**
* Change the right X value of the controller's joystick.
*
* @param value the new value
*/
void SetRightX(double value);
/**
* Change the right Y value of the controller's joystick.
*
* @param value the new value
*/
void SetRightY(double value);
/**
* Change the value of the left trigger axis on the controller.
*
* @param value the new value
*/
void SetLeftTriggerAxis(double value);
/**
* Change the value of the right trigger axis on the controller.
*
* @param value the new value
*/
void SetRightTriggerAxis(double value);
/**
* Change the value of the South Face button on the controller.
*
* @param value the new value
*/
void SetSouthFaceButton(bool value);
/**
* Change the value of the East Face button on the controller.
*
* @param value the new value
*/
void SetEastFaceButton(bool value);
/**
* Change the value of the West Face button on the controller.
*
* @param value the new value
*/
void SetWestFaceButton(bool value);
/**
* Change the value of the North Face button on the controller.
*
* @param value the new value
*/
void SetNorthFaceButton(bool value);
/**
* Change the value of the Back button on the controller.
*
* @param value the new value
*/
void SetBackButton(bool value);
/**
* Change the value of the Guide button on the controller.
*
* @param value the new value
*/
void SetGuideButton(bool value);
/**
* Change the value of the Start button on the controller.
*
* @param value the new value
*/
void SetStartButton(bool value);
/**
* Change the value of the left stick button on the controller.
*
* @param value the new value
*/
void SetLeftStickButton(bool value);
/**
* Change the value of the right stick button on the controller.
*
* @param value the new value
*/
void SetRightStickButton(bool value);
/**
* Change the value of the right shoulder button on the controller.
*
* @param value the new value
*/
void SetLeftShoulderButton(bool value);
/**
* Change the value of the right shoulder button on the controller.
*
* @param value the new value
*/
void SetRightShoulderButton(bool value);
/**
* Change the value of the D-pad up button on the controller.
*
* @param value the new value
*/
void SetDpadUpButton(bool value);
/**
* Change the value of the D-pad down button on the controller.
*
* @param value the new value
*/
void SetDpadDownButton(bool value);
/**
* Change the value of the D-pad left button on the controller.
*
* @param value the new value
*/
void SetDpadLeftButton(bool value);
/**
* Change the value of the D-pad right button on the controller.
*
* @param value the new value
*/
void SetDpadRightButton(bool value);
/**
* Change the value of the Miscellaneous 1 button on the controller.
*
* @param value the new value
*/
void SetMisc1Button(bool value);
/**
* Change the value of the Right Paddle 1 button on the controller.
*
* @param value the new value
*/
void SetRightPaddle1Button(bool value);
/**
* Change the value of the Left Paddle 1 button on the controller.
*
* @param value the new value
*/
void SetLeftPaddle1Button(bool value);
/**
* Change the value of the Right Paddle 2 button on the controller.
*
* @param value the new value
*/
void SetRightPaddle2Button(bool value);
/**
* Change the value of the Left Paddle 2 button on the controller.
*
* @param value the new value
*/
void SetLeftPaddle2Button(bool value);
/**
* Change the value of the Touchpad button on the controller.
*
* @param value the new value
*/
void SetTouchpadButton(bool value);
/**
* Change the value of the Miscellaneous 2 button on the controller.
*
* @param value the new value
*/
void SetMisc2Button(bool value);
/**
* Change the value of the Miscellaneous 3 button on the controller.
*
* @param value the new value
*/
void SetMisc3Button(bool value);
/**
* Change the value of the Miscellaneous 4 button on the controller.
*
* @param value the new value
*/
void SetMisc4Button(bool value);
/**
* Change the value of the Miscellaneous 5 button on the controller.
*
* @param value the new value
*/
void SetMisc5Button(bool value);
/**
* Change the value of the Miscellaneous 6 button on the controller.
*
* @param value the new value
*/
void SetMisc6Button(bool value);
};
} // namespace sim
} // namespace frc

View File

@@ -0,0 +1,143 @@
// 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.
#pragma once
#include <stdint.h>
#include "frc/DriverStation.h"
#include "frc/GenericHID.h"
namespace frc {
class GenericHID;
namespace sim {
/**
* Class to control a simulated generic joystick.
*/
class GenericHIDSim {
public:
/**
* Constructs from a GenericHID object.
*
* @param joystick joystick to simulate
*/
explicit GenericHIDSim(const GenericHID& joystick);
/**
* Constructs from a joystick port number.
*
* @param port port number
*/
explicit GenericHIDSim(int port);
/**
* Updates joystick data so that new values are visible to the user program.
*/
void NotifyNewData();
/**
* Set the value of a given button.
*
* @param button the button to set
* @param value the new value
*/
void SetRawButton(int button, bool value);
/**
* Set the value of a given axis.
*
* @param axis the axis to set
* @param value the new value
*/
void SetRawAxis(int axis, double value);
/**
* Set the value of a given POV.
*
* @param pov the POV to set
* @param value the new value
*/
void SetPOV(int pov, DriverStation::POVDirection value);
/**
* Set the value of the default POV (port 0).
*
* @param value the new value
*/
void SetPOV(DriverStation::POVDirection value);
void SetAxesMaximumIndex(int maximumIndex);
/**
* Set the axis count of this device.
*
* @param count the new axis count
*/
void SetAxesAvailable(int count);
void SetPOVsMaximumIndex(int maximumIndex);
/**
* Set the POV count of this device.
*
* @param count the new POV count
*/
void SetPOVsAvailable(int count);
void SetButtonsMaximumIndex(int maximumIndex);
/**
* Set the button count of this device.
*
* @param count the new button count
*/
void SetButtonsAvailable(uint64_t count);
/**
* Set the type of this device.
*
* @param type the new device type
*/
void SetType(GenericHID::HIDType type);
/**
* Set the name of this device.
*
* @param name the new device name
*/
void SetName(const char* name);
/**
* Read the output of a button.
*
* @param outputNumber the button number
* @return the value of the button (true = pressed)
*/
bool GetOutput(int outputNumber);
/**
* Get the encoded 16-bit integer that passes button values.
*
* @return the button values
*/
int64_t GetOutputs();
/**
* Get the joystick rumble.
*
* @param type the rumble to read
* @return the rumble value
*/
double GetRumble(GenericHID::RumbleType type);
protected:
/// GenericHID port.
int m_port;
};
} // namespace sim
} // namespace frc

View File

@@ -0,0 +1,88 @@
// 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.
#pragma once
#include "frc/simulation/GenericHIDSim.h"
namespace frc {
class Joystick;
namespace sim {
/**
* Class to control a simulated joystick.
*/
class JoystickSim : public GenericHIDSim {
public:
/**
* Constructs from a Joystick object.
*
* @param joystick joystick to simulate
*/
explicit JoystickSim(const Joystick& joystick);
/**
* Constructs from a joystick port number.
*
* @param port port number
*/
explicit JoystickSim(int port);
/**
* Set the X value of the joystick.
*
* @param value the new X value
*/
void SetX(double value);
/**
* Set the Y value of the joystick.
*
* @param value the new Y value
*/
void SetY(double value);
/**
* Set the Z value of the joystick.
*
* @param value the new Z value
*/
void SetZ(double value);
/**
* Set the twist value of the joystick.
*
* @param value the new twist value
*/
void SetTwist(double value);
/**
* Set the throttle value of the joystick.
*
* @param value the new throttle value
*/
void SetThrottle(double value);
/**
* Set the trigger value of the joystick.
*
* @param state the new value
*/
void SetTrigger(bool state);
/**
* Set the top state of the joystick.
*
* @param state the new state
*/
void SetTop(bool state);
private:
const Joystick* m_joystick = nullptr;
};
} // namespace sim
} // namespace frc

View File

@@ -0,0 +1,167 @@
// 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.
#pragma once
#include <array>
#include <units/current.h>
#include <units/time.h>
#include "frc/EigenCore.h"
#include "frc/StateSpaceUtil.h"
#include "frc/system/LinearSystem.h"
namespace frc::sim {
/**
* This class helps simulate linear systems. To use this class, do the following
* in the simulationPeriodic() method.
*
* Call the SetInput() method with the inputs to your system (generally
* voltage). Call the Update() method to update the simulation. Set simulated
* sensor readings with the simulated positions in the GetOutput() method.
*
* @tparam States Number of states of the system.
* @tparam Inputs Number of inputs to the system.
* @tparam Outputs Number of outputs of the system.
*/
template <int States, int Inputs, int Outputs>
class LinearSystemSim {
public:
/**
* Creates a simulated generic linear system.
*
* @param system The system to simulate.
* @param measurementStdDevs The standard deviations of the measurements.
*/
explicit LinearSystemSim(
const LinearSystem<States, Inputs, Outputs>& system,
const std::array<double, Outputs>& measurementStdDevs = {})
: m_plant(system), m_measurementStdDevs(measurementStdDevs) {
m_x = Vectord<States>::Zero();
m_y = Vectord<Outputs>::Zero();
m_u = Vectord<Inputs>::Zero();
}
virtual ~LinearSystemSim() = default;
/**
* Updates the simulation.
*
* @param dt The time between updates.
*/
void Update(units::second_t dt) {
// Update x. By default, this is the linear system dynamics xₖ₊₁ = Axₖ +
// Buₖ.
m_x = UpdateX(m_x, m_u, dt);
// yₖ = Cxₖ + Duₖ
m_y = m_plant.CalculateY(m_x, m_u);
// Add noise. If the user did not pass a noise vector to the
// constructor, then this method will not do anything because
// the standard deviations default to zero.
m_y += frc::MakeWhiteNoiseVector<Outputs>(m_measurementStdDevs);
}
/**
* Returns the current output of the plant.
*
* @return The current output of the plant.
*/
const Vectord<Outputs>& GetOutput() const { return m_y; }
/**
* Returns an element of the current output of the plant.
*
* @param row The row to return.
* @return An element of the current output of the plant.
*/
double GetOutput(int row) const { return m_y(row); }
/**
* Sets the system inputs (usually voltages).
*
* @param u The system inputs.
*/
void SetInput(const Vectord<Inputs>& u) { m_u = u; }
/**
* Sets the system inputs.
*
* @param row The row in the input matrix to set.
* @param value The value to set the row to.
*/
void SetInput(int row, double value) { m_u(row, 0) = value; }
/**
* Returns the current input of the plant.
*
* @return The current input of the plant.
*/
const Vectord<Inputs>& GetInput() const { return m_u; }
/**
* Returns an element of the current input of the plant.
*
* @param row The row to return.
* @return An element of the current input of the plant.
*/
double GetInput(int row) const { return m_u(row); }
/**
* Sets the system state.
*
* @param state The new state.
*/
void SetState(const Vectord<States>& state) {
m_x = state;
// Update the output to reflect the new state.
//
// yₖ = Cxₖ + Duₖ
m_y = m_plant.CalculateY(m_x, m_u);
}
protected:
/**
* Updates the state estimate of the system.
*
* @param currentXhat The current state estimate.
* @param u The system inputs (usually voltage).
* @param dt The time difference between controller updates.
*/
virtual Vectord<States> UpdateX(const Vectord<States>& currentXhat,
const Vectord<Inputs>& u,
units::second_t dt) {
return m_plant.CalculateX(currentXhat, u, dt);
}
/**
* Clamp the input vector such that no element exceeds the given voltage. If
* any does, the relative magnitudes of the input will be maintained.
*
* @param maxInput The maximum magnitude of the input vector after clamping.
*/
void ClampInput(double maxInput) {
m_u = frc::DesaturateInputVector<Inputs>(m_u, maxInput);
}
/// The plant that represents the linear system.
LinearSystem<States, Inputs, Outputs> m_plant;
/// State vector.
Vectord<States> m_x;
/// Input vector.
Vectord<Inputs> m_u;
/// Output vector.
Vectord<Outputs> m_y;
/// The standard deviations of measurements, used for adding noise to the
/// measurements.
std::array<double, Outputs> m_measurementStdDevs;
};
} // namespace frc::sim

View File

@@ -0,0 +1,30 @@
// 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.
#pragma once
#include <hal/SimDevice.h>
#include <units/length.h>
#include "frc/motorcontrol/PWMMotorController.h"
namespace frc {
class PWMMotorController;
namespace sim {
class PWMMotorControllerSim {
public:
explicit PWMMotorControllerSim(const PWMMotorController& motorctrl);
explicit PWMMotorControllerSim(int channel);
double GetSpeed() const;
private:
hal::SimDouble m_simSpeed;
};
} // namespace sim
} // namespace frc

View File

@@ -0,0 +1,121 @@
// 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.
#pragma once
#include <memory>
#include "frc/simulation/CallbackStore.h"
namespace frc {
class PWM;
class PWMMotorController;
namespace sim {
/**
* Class to control a simulated PWM output.
*/
class PWMSim {
public:
/**
* Constructs from a PWM object.
*
* @param pwm PWM to simulate
*/
explicit PWMSim(const PWM& pwm);
/**
* Constructs from a PWM channel number.
*
* @param channel Channel number
*/
explicit PWMSim(int channel);
/**
* Register a callback to be run when the PWM is initialized.
*
* @param callback the callback
* @param initialNotify whether to run the callback with the initial state
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
std::unique_ptr<CallbackStore> RegisterInitializedCallback(
NotifyCallback callback, bool initialNotify);
/**
* Check whether the PWM has been initialized.
*
* @return true if initialized
*/
bool GetInitialized() const;
/**
* Define whether the PWM has been initialized.
*
* @param initialized whether this object is initialized
*/
void SetInitialized(bool initialized);
/**
* Register a callback to be run when the PWM pulse microsecond value changes.
*
* @param callback the callback
* @param initialNotify whether to run the callback with the initial value
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
std::unique_ptr<CallbackStore> RegisterPulseMicrosecondCallback(
NotifyCallback callback, bool initialNotify);
/**
* Get the PWM pulse microsecond value.
*
* @return the PWM pulse microsecond value
*/
int32_t GetPulseMicrosecond() const;
/**
* Set the PWM pulse microsecond value.
*
* @param microsecondPulseTime the PWM pulse microsecond value
*/
void SetPulseMicrosecond(int32_t microsecondPulseTime);
/**
* Register a callback to be run when the PWM period scale changes.
*
* @param callback the callback
* @param initialNotify whether to run the callback with the initial value
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
std::unique_ptr<CallbackStore> RegisterOutputPeriodCallback(
NotifyCallback callback, bool initialNotify);
/**
* Get the PWM period scale.
*
* @return the PWM period scale
*/
int GetOutputPeriod() const;
/**
* Set the PWM period scale.
*
* @param period the PWM period scale
*/
void SetOutputPeriod(int period);
/**
* Reset all simulation data.
*/
void ResetData();
private:
int m_index;
};
} // namespace sim
} // namespace frc

View File

@@ -0,0 +1,198 @@
// 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.
#pragma once
#include <memory>
#include "frc/PneumaticsBase.h"
#include "frc/PneumaticsModuleType.h"
#include "frc/simulation/CallbackStore.h"
namespace frc::sim {
class PneumaticsBaseSim {
public:
virtual ~PneumaticsBaseSim() = default;
static std::shared_ptr<PneumaticsBaseSim> GetForType(
int module, PneumaticsModuleType type);
/**
* Check whether the PCM/PH has been initialized.
*
* @return true if initialized
*/
virtual bool GetInitialized() const = 0;
/**
* Define whether the PCM/PH has been initialized.
*
* @param initialized true for initialized
*/
virtual void SetInitialized(bool initialized) = 0;
/**
* Register a callback to be run when the PCM/PH is initialized.
*
* @param callback the callback
* @param initialNotify whether to run the callback with the initial state
* @return the {@link CallbackStore} object associated with this callback.
* Save a reference to this object; it being deconstructed cancels the
* callback.
*/
[[nodiscard]]
virtual std::unique_ptr<CallbackStore> RegisterInitializedCallback(
NotifyCallback callback, bool initialNotify) = 0;
/**
* Check if the compressor is on.
*
* @return true if the compressor is active
*/
virtual bool GetCompressorOn() const = 0;
/**
* Set whether the compressor is active.
*
* @param compressorOn the new value
*/
virtual void SetCompressorOn(bool compressorOn) = 0;
/**
* Register a callback to be run when the compressor activates.
*
* @param callback the callback
* @param initialNotify whether to run the callback with the initial state
* @return the {@link CallbackStore} object associated with this callback.
* Save a reference to this object; it being deconstructed cancels the
* callback.
*/
[[nodiscard]]
virtual std::unique_ptr<CallbackStore> RegisterCompressorOnCallback(
NotifyCallback callback, bool initialNotify) = 0;
/**
* Check the solenoid output on a specific channel.
*
* @param channel the channel to check
* @return the solenoid output
*/
virtual bool GetSolenoidOutput(int channel) const = 0;
/**
* Change the solenoid output on a specific channel.
*
* @param channel the channel to check
* @param solenoidOutput the new solenoid output
*/
virtual void SetSolenoidOutput(int channel, bool solenoidOutput) = 0;
/**
* Register a callback to be run when the solenoid output on a channel
* changes.
*
* @param channel the channel to monitor
* @param callback the callback
* @param initialNotify should the callback be run with the initial value
* @return the {@link CallbackStore} object associated with this callback.
* Save a reference to this object; it being deconstructed cancels the
* callback.
*/
[[nodiscard]]
virtual std::unique_ptr<CallbackStore> RegisterSolenoidOutputCallback(
int channel, NotifyCallback callback, bool initialNotify) = 0;
/**
* Check the value of the pressure switch.
*
* @return the pressure switch value
*/
virtual bool GetPressureSwitch() const = 0;
/**
* Set the value of the pressure switch.
*
* @param pressureSwitch the new value
*/
virtual void SetPressureSwitch(bool pressureSwitch) = 0;
/**
* Register a callback to be run whenever the pressure switch value changes.
*
* @param callback the callback
* @param initialNotify whether the callback should be called with the initial
* value
* @return the {@link CallbackStore} object associated with this callback.
* Save a reference to this object; it being deconstructed cancels the
* callback.
*/
[[nodiscard]]
virtual std::unique_ptr<CallbackStore> RegisterPressureSwitchCallback(
NotifyCallback callback, bool initialNotify) = 0;
/**
* Read the compressor current.
*
* @return the current of the compressor connected to this module
*/
virtual double GetCompressorCurrent() const = 0;
/**
* Set the compressor current.
*
* @param compressorCurrent the new compressor current
*/
virtual void SetCompressorCurrent(double compressorCurrent) = 0;
/**
* Register a callback to be run whenever the compressor current changes.
*
* @param callback the callback
* @param initialNotify whether to call the callback with the initial state
* @return the {@link CallbackStore} object associated with this callback.
* Save a reference to this object; it being deconstructed cancels the
* callback.
*/
[[nodiscard]]
virtual std::unique_ptr<CallbackStore> RegisterCompressorCurrentCallback(
NotifyCallback callback, bool initialNotify) = 0;
/**
* Get the current value of all solenoid outputs.
*
* @return the solenoid outputs (1 bit per output)
*/
virtual uint8_t GetAllSolenoidOutputs() const = 0;
/**
* Change all of the solenoid outputs.
*
* @param outputs the new solenoid outputs (1 bit per output)
*/
virtual void SetAllSolenoidOutputs(uint8_t outputs) = 0;
/** Reset all simulation data for this object. */
virtual void ResetData() = 0;
protected:
/// PneumaticsBase index.
const int m_index;
/**
* Constructs a PneumaticsBaseSim with the given index.
*
* @param index The index.
*/
explicit PneumaticsBaseSim(const int index);
/**
* Constructs a PneumaticsBaseSim for the given module.
*
* @param module The module.
*/
explicit PneumaticsBaseSim(const PneumaticsBase& module);
};
} // namespace frc::sim

View File

@@ -0,0 +1,171 @@
// 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.
#pragma once
#include <memory>
#include "frc/simulation/CallbackStore.h"
namespace frc {
class PowerDistribution;
namespace sim {
/**
* Class to control a simulated Power Distribution Panel (PowerDistribution).
*/
class PowerDistributionSim {
public:
/**
* Constructs from a PowerDistribution module number (CAN ID).
*
* @param module module number
*/
explicit PowerDistributionSim(int module = 0);
/**
* Constructs from a PowerDistribution object.
*
* @param pdp PowerDistribution to simulate
*/
explicit PowerDistributionSim(const PowerDistribution& pdp);
/**
* Register a callback to be run when the PowerDistribution is initialized.
*
* @param callback the callback
* @param initialNotify whether to run the callback with the initial state
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
std::unique_ptr<CallbackStore> RegisterInitializedCallback(
NotifyCallback callback, bool initialNotify);
/**
* Check whether the PowerDistribution has been initialized.
*
* @return true if initialized
*/
bool GetInitialized() const;
/**
* Define whether the PowerDistribution has been initialized.
*
* @param initialized whether this object is initialized
*/
void SetInitialized(bool initialized);
/**
* Register a callback to be run whenever the PowerDistribution temperature
* changes.
*
* @param callback the callback
* @param initialNotify whether to call the callback with the initial state
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
std::unique_ptr<CallbackStore> RegisterTemperatureCallback(
NotifyCallback callback, bool initialNotify);
/**
* Check the temperature of the PowerDistribution.
*
* @return the PowerDistribution temperature
*/
double GetTemperature() const;
/**
* Define the PowerDistribution temperature.
*
* @param temperature the new PowerDistribution temperature
*/
void SetTemperature(double temperature);
/**
* Register a callback to be run whenever the PowerDistribution voltage
* changes.
*
* @param callback the callback
* @param initialNotify whether to call the callback with the initial state
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
std::unique_ptr<CallbackStore> RegisterVoltageCallback(
NotifyCallback callback, bool initialNotify);
/**
* Check the PowerDistribution voltage.
*
* @return the PowerDistribution voltage.
*/
double GetVoltage() const;
/**
* Set the PowerDistribution voltage.
*
* @param voltage the new PowerDistribution voltage
*/
void SetVoltage(double voltage);
/**
* Register a callback to be run whenever the current of a specific channel
* changes.
*
* @param channel the channel
* @param callback the callback
* @param initialNotify whether to call the callback with the initial state
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
std::unique_ptr<CallbackStore> RegisterCurrentCallback(
int channel, NotifyCallback callback, bool initialNotify);
/**
* Read the current in one of the PowerDistribution channels.
*
* @param channel the channel to check
* @return the current in the given channel
*/
double GetCurrent(int channel) const;
/**
* Change the current in the given channel.
*
* @param channel the channel to edit
* @param current the new current for the channel
*/
void SetCurrent(int channel, double current);
/**
* Read the current of all of the PowerDistribution channels.
*
* @param currents output array; set to the current in each channel. The
* array must be big enough to hold all the PowerDistribution
* channels
* @param length length of output array
*/
void GetAllCurrents(double* currents, int length) const;
/**
* Change the current in all of the PowerDistribution channels.
*
* @param currents array containing the current values for each channel. The
* array must be big enough to hold all the PowerDistribution
* channels
* @param length length of array
*/
void SetAllCurrents(const double* currents, int length);
/**
* Reset all PowerDistribution simulation data.
*/
void ResetData();
private:
int m_index;
};
} // namespace sim
} // namespace frc

View File

@@ -0,0 +1,123 @@
// 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.
#pragma once
#include <memory>
#include "frc/PneumaticsBase.h"
#include "frc/simulation/CallbackStore.h"
#include "frc/simulation/PneumaticsBaseSim.h"
namespace frc {
class Compressor;
namespace sim {
/**
* Class to control a simulated Pneumatic Control Module (PCM).
*/
class REVPHSim : public PneumaticsBaseSim {
public:
/**
* Constructs with the default PCM module number (CAN ID).
*/
REVPHSim();
/**
* Constructs from a PCM module number (CAN ID).
*
* @param module module number
*/
explicit REVPHSim(int module);
explicit REVPHSim(const PneumaticsBase& pneumatics);
~REVPHSim() override = default;
[[nodiscard]]
std::unique_ptr<CallbackStore> RegisterInitializedCallback(
NotifyCallback callback, bool initialNotify) override;
bool GetInitialized() const override;
void SetInitialized(bool solenoidInitialized) override;
[[nodiscard]]
std::unique_ptr<CallbackStore> RegisterSolenoidOutputCallback(
int channel, NotifyCallback callback, bool initialNotify) override;
bool GetSolenoidOutput(int channel) const override;
void SetSolenoidOutput(int channel, bool solenoidOutput) override;
[[nodiscard]]
std::unique_ptr<CallbackStore> RegisterCompressorOnCallback(
NotifyCallback callback, bool initialNotify) override;
/**
* Check if the compressor is on.
*
* @return true if the compressor is active
*/
bool GetCompressorOn() const override;
/**
* Set whether the compressor is active.
*
* @param compressorOn the new value
*/
void SetCompressorOn(bool compressorOn) override;
/**
* Register a callback to be run whenever the closed loop state changes.
*
* @param callback the callback
* @param initialNotify whether the callback should be called with the
* initial value
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
std::unique_ptr<CallbackStore> RegisterCompressorConfigTypeCallback(
NotifyCallback callback, bool initialNotify);
/**
* Check whether the closed loop compressor control is active.
*
* @return compressor config type
*/
int GetCompressorConfigType() const;
/**
* Turn on/off the closed loop control of the compressor.
*
* @param compressorConfigType compressor config type
*/
void SetCompressorConfigType(int compressorConfigType);
[[nodiscard]]
std::unique_ptr<CallbackStore> RegisterPressureSwitchCallback(
NotifyCallback callback, bool initialNotify) override;
bool GetPressureSwitch() const override;
void SetPressureSwitch(bool pressureSwitch) override;
[[nodiscard]]
std::unique_ptr<CallbackStore> RegisterCompressorCurrentCallback(
NotifyCallback callback, bool initialNotify) override;
double GetCompressorCurrent() const override;
void SetCompressorCurrent(double compressorCurrent) override;
uint8_t GetAllSolenoidOutputs() const override;
void SetAllSolenoidOutputs(uint8_t outputs) override;
void ResetData() override;
};
} // namespace sim
} // namespace frc

View File

@@ -0,0 +1,262 @@
// 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.
#pragma once
#include <memory>
#include <string>
#include <units/current.h>
#include <units/temperature.h>
#include <units/voltage.h>
#include "frc/RobotController.h"
#include "frc/simulation/CallbackStore.h"
namespace frc::sim {
/**
* A utility class to control a simulated RoboRIO.
*/
class RoboRioSim {
public:
/**
* Register a callback to be run whenever the Vin voltage changes.
*
* @param callback the callback
* @param initialNotify whether to call the callback with the initial state
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
static std::unique_ptr<CallbackStore> RegisterVInVoltageCallback(
NotifyCallback callback, bool initialNotify);
/**
* Measure the Vin voltage.
*
* @return the Vin voltage
*/
static units::volt_t GetVInVoltage();
/**
* Define the Vin voltage.
*
* @param vInVoltage the new voltage
*/
static void SetVInVoltage(units::volt_t vInVoltage);
/**
* Register a callback to be run whenever the 3.3V rail voltage changes.
*
* @param callback the callback
* @param initialNotify whether the callback should be called with the
* initial value
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
static std::unique_ptr<CallbackStore> RegisterUserVoltage3V3Callback(
NotifyCallback callback, bool initialNotify);
/**
* Measure the 3.3V rail voltage.
*
* @return the 3.3V rail voltage
*/
static units::volt_t GetUserVoltage3V3();
/**
* Define the 3.3V rail voltage.
*
* @param userVoltage3V3 the new voltage
*/
static void SetUserVoltage3V3(units::volt_t userVoltage3V3);
/**
* Register a callback to be run whenever the 3.3V rail current changes.
*
* @param callback the callback
* @param initialNotify whether the callback should be called with the
* initial value
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
static std::unique_ptr<CallbackStore> RegisterUserCurrent3V3Callback(
NotifyCallback callback, bool initialNotify);
/**
* Measure the 3.3V rail current.
*
* @return the 3.3V rail current
*/
static units::ampere_t GetUserCurrent3V3();
/**
* Define the 3.3V rail current.
*
* @param userCurrent3V3 the new current
*/
static void SetUserCurrent3V3(units::ampere_t userCurrent3V3);
/**
* Register a callback to be run whenever the 3.3V rail active state changes.
*
* @param callback the callback
* @param initialNotify whether the callback should be called with the
* initial state
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
static std::unique_ptr<CallbackStore> RegisterUserActive3V3Callback(
NotifyCallback callback, bool initialNotify);
/**
* Get the 3.3V rail active state.
*
* @return true if the 3.3V rail is active
*/
static bool GetUserActive3V3();
/**
* Set the 3.3V rail active state.
*
* @param userActive3V3 true to make rail active
*/
static void SetUserActive3V3(bool userActive3V3);
/**
* Register a callback to be run whenever the 3.3V rail number of faults
* changes.
*
* @param callback the callback
* @param initialNotify whether the callback should be called with the
* initial value
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
static std::unique_ptr<CallbackStore> RegisterUserFaults3V3Callback(
NotifyCallback callback, bool initialNotify);
/**
* Get the 3.3V rail number of faults.
*
* @return number of faults
*/
static int GetUserFaults3V3();
/**
* Set the 3.3V rail number of faults.
*
* @param userFaults3V3 number of faults
*/
static void SetUserFaults3V3(int userFaults3V3);
/**
* Register a callback to be run whenever the brownout voltage changes.
*
* @param callback the callback
* @param initialNotify whether to call the callback with the initial state
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
static std::unique_ptr<CallbackStore> RegisterBrownoutVoltageCallback(
NotifyCallback callback, bool initialNotify);
/**
* Measure the brownout voltage.
*
* @return the brownout voltage
*/
static units::volt_t GetBrownoutVoltage();
/**
* Define the brownout voltage.
*
* @param brownoutVoltage the new voltage
*/
static void SetBrownoutVoltage(units::volt_t brownoutVoltage);
/**
* Register a callback to be run whenever the cpu temp changes.
*
* @param callback the callback
* @param initialNotify whether to call the callback with the initial state
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
static std::unique_ptr<CallbackStore> RegisterCPUTempCallback(
NotifyCallback callback, bool initialNotify);
/**
* Get the cpu temp.
*
* @return the cpu temp.
*/
static units::celsius_t GetCPUTemp();
/**
* Define the cpu temp.
*
* @param cpuTemp the new cpu temp.
*/
static void SetCPUTemp(units::celsius_t cpuTemp);
/**
* Register a callback to be run whenever the team number changes.
*
* @param callback the callback
* @param initialNotify whether to call the callback with the initial state
* @return the CallbackStore object associated with this callback
*/
[[nodiscard]]
static std::unique_ptr<CallbackStore> RegisterTeamNumberCallback(
NotifyCallback callback, bool initialNotify);
/**
* Get the team number.
*
* @return the team number.
*/
static int32_t GetTeamNumber();
/**
* Set the team number.
*
* @param teamNumber the new team number.
*/
static void SetTeamNumber(int32_t teamNumber);
/**
* Get the serial number.
*
* @return The serial number.
*/
static std::string GetSerialNumber();
/**
* Set the serial number.
*
* @param serialNumber The serial number.
*/
static void SetSerialNumber(std::string_view serialNumber);
/**
* Get the comments.
*
* @return The comments.
*/
static std::string GetComments();
/**
* Set the comments.
*
* @param comments The comments.
*/
static void SetComments(std::string_view comments);
/**
* Reset all simulation data.
*/
static void ResetData();
};
} // namespace frc::sim

View File

@@ -0,0 +1,46 @@
// 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.
#pragma once
#include <string_view>
#include <networktables/NetworkTableInstance.h>
#include <networktables/StringTopic.h>
#include "frc/RobotBase.h"
namespace frc::sim {
/**
* Class that facilitates control of a SendableChooser's selected option in
* simulation.
*/
class SendableChooserSim {
public:
/**
* Constructs a SendableChooserSim.
*
* @param path The path where the SendableChooser is published.
*/
explicit SendableChooserSim(std::string_view path);
/**
* Constructs a SendableChooserSim.
*
* @param inst The NetworkTables instance.
* @param path The path where the SendableChooser is published.
*/
SendableChooserSim(nt::NetworkTableInstance inst, std::string_view path);
/**
* Set the selected option.
* @param option The option.
*/
void SetSelected(std::string_view option);
private:
nt::StringPublisher m_publisher;
};
} // namespace frc::sim

View File

@@ -0,0 +1,42 @@
// 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.
#pragma once
#include <hal/SimDevice.h>
#include <units/length.h>
#include "frc/SharpIR.h"
namespace frc {
/** Simulation class for Sharp IR sensors. */
class SharpIRSim {
public:
/**
* Constructor.
*
* @param sharpIR The real sensor to simulate
*/
explicit SharpIRSim(const SharpIR& sharpIR);
/**
* Constructor.
*
* @param channel Analog channel for this sensor
*/
explicit SharpIRSim(int channel);
/**
* Set the range returned by the distance sensor.
*
* @param range range of the target returned by the sensor
*/
void SetRange(units::meter_t range);
private:
hal::SimDouble m_simRange;
};
} // namespace frc

View File

@@ -0,0 +1,162 @@
// 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.
#pragma once
#include <functional>
#include <string>
#include <vector>
#include <hal/SimDevice.h>
#include <hal/simulation/SimDeviceData.h>
namespace frc::sim {
/**
* Class to control the simulation side of a SimDevice.
*/
class SimDeviceSim {
public:
/**
* Constructs a SimDeviceSim.
*
* @param name name of the SimDevice
*/
explicit SimDeviceSim(const char* name);
/**
* Constructs a SimDeviceSim.
*
* @param name name of the SimDevice
* @param index device index number to append to name
*/
SimDeviceSim(const char* name, int index);
/**
* Constructs a SimDeviceSim.
*
* @param name name of the SimDevice
* @param index device index number to append to name
* @param channel device channel number to append to name
*/
SimDeviceSim(const char* name, int index, int channel);
/**
* Constructs a SimDeviceSim.
*
* @param handle the low level handle for the corresponding SimDevice.
*/
explicit SimDeviceSim(HAL_SimDeviceHandle handle);
/**
* Get the name of this object.
*
* @return name
*/
std::string GetName() const;
/**
* Get the property object with the given name.
*
* @param name the property name
* @return the property object
*/
hal::SimValue GetValue(const char* name) const;
/**
* Get the property object with the given name.
*
* @param name the property name
* @return the property object
*/
hal::SimInt GetInt(const char* name) const;
/**
* Get the property object with the given name.
*
* @param name the property name
* @return the property object
*/
hal::SimLong GetLong(const char* name) const;
/**
* Get the property object with the given name.
*
* @param name the property name
* @return the property object
*/
hal::SimDouble GetDouble(const char* name) const;
/**
* Get the property object with the given name.
*
* @param name the property name
* @return the property object
*/
hal::SimEnum GetEnum(const char* name) const;
/**
* Get the property object with the given name.
*
* @param name the property name
* @return the property object
*/
hal::SimBoolean GetBoolean(const char* name) const;
/**
* Get all options for the given enum.
*
* @param val the enum
* @return names of the different values for that enum
*/
static std::vector<std::string> GetEnumOptions(hal::SimEnum val);
/**
* Get all properties.
*
* @param callback callback called for each property (SimValue). Signature
* of the callback must be const char*, HAL_SimValueHandle,
* int, const HAL_Value*
*/
template <typename F>
void EnumerateValues(F callback) const {
return HALSIM_EnumerateSimValues(
m_handle, &callback,
[](const char* name, void* param, HAL_SimValueHandle handle,
int direction, const struct HAL_Value* value) {
std::invoke(*static_cast<F*>(param), name, handle, direction, value);
});
}
/**
* Get the raw handle of this object.
*
* @return the handle used to refer to this object
*/
operator HAL_SimDeviceHandle() const { return m_handle; } // NOLINT
/**
* Get all sim devices with the given prefix.
*
* @param prefix the prefix to filter sim devices
* @param callback callback function to call for each sim device
*/
template <typename F>
static void EnumerateDevices(const char* prefix, F callback) {
return HALSIM_EnumerateSimDevices(
prefix, &callback,
[](const char* name, void* param, HAL_SimDeviceHandle handle) {
std::invoke(*static_cast<F*>(param), name, handle);
});
}
/**
* Reset all SimDevice data.
*/
static void ResetData();
private:
HAL_SimDeviceHandle m_handle;
};
} // namespace frc::sim

View File

@@ -0,0 +1,63 @@
// 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.
#pragma once
#include <stdint.h>
#include <hal/HALBase.h>
#include <units/time.h>
namespace frc::sim {
/**
* Override the HAL runtime type (simulated/real).
*
* @param type runtime type
*/
void SetRuntimeType(HAL_RuntimeType type);
void WaitForProgramStart();
void SetProgramStarted();
bool GetProgramStarted();
/**
* Restart the simulator time.
*/
void RestartTiming();
/**
* Pause the simulator time.
*/
void PauseTiming();
/**
* Resume the simulator time.
*/
void ResumeTiming();
/**
* Check if the simulator time is paused.
*
* @return true if paused
*/
bool IsTimingPaused();
/**
* Advance the simulator time and wait for all notifiers to run.
*
* @param delta the amount to advance (in seconds)
*/
void StepTiming(units::second_t delta);
/**
* Advance the simulator time and return immediately.
*
* @param delta the amount to advance (in seconds)
*/
void StepTimingAsync(units::second_t delta);
} // namespace frc::sim

View File

@@ -0,0 +1,171 @@
// 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.
#pragma once
#include <array>
#include <units/angle.h>
#include <units/length.h>
#include <units/mass.h>
#include <units/moment_of_inertia.h>
#include "frc/simulation/LinearSystemSim.h"
#include "frc/system/plant/DCMotor.h"
namespace frc::sim {
/**
* Represents a simulated arm mechanism.
*/
class SingleJointedArmSim : public LinearSystemSim<2, 1, 2> {
public:
/**
* Creates a simulated arm mechanism.
*
* @param system The system representing this arm. This system can
* be created with
* LinearSystemId::SingleJointedArmSystem().
* @param gearbox The type and number of motors on the arm gearbox.
* @param gearing The gear ratio of the arm (numbers greater than 1
* represent reductions).
* @param armLength The length of the arm.
* @param minAngle The minimum angle that the arm is capable of.
* @param maxAngle The maximum angle that the arm is capable of.
* @param simulateGravity Whether gravity should be simulated or not.
* @param startingAngle The initial position of the arm.
* @param measurementStdDevs The standard deviations of the measurements.
*/
SingleJointedArmSim(const LinearSystem<2, 1, 2>& system,
const DCMotor& gearbox, double gearing,
units::meter_t armLength, units::radian_t minAngle,
units::radian_t maxAngle, bool simulateGravity,
units::radian_t startingAngle,
const std::array<double, 2>& measurementStdDevs = {0.0,
0.0});
/**
* Creates a simulated arm mechanism.
*
* @param gearbox The type and number of motors on the arm gearbox.
* @param gearing The gear ratio of the arm (numbers greater than 1
* represent reductions).
* @param moi The moment of inertia of the arm. This can be
* calculated from CAD software.
* @param armLength The length of the arm.
* @param minAngle The minimum angle that the arm is capable of.
* @param maxAngle The maximum angle that the arm is capable of.
* @param simulateGravity Whether gravity should be simulated or not.
* @param startingAngle The initial position of the arm.
* @param measurementStdDevs The standard deviation of the measurement noise.
*/
SingleJointedArmSim(const DCMotor& gearbox, double gearing,
units::kilogram_square_meter_t moi,
units::meter_t armLength, units::radian_t minAngle,
units::radian_t maxAngle, bool simulateGravity,
units::radian_t startingAngle,
const std::array<double, 2>& measurementStdDevs = {0.0,
0.0});
using LinearSystemSim::SetState;
/**
* Sets the arm's state. The new angle will be limited between the minimum and
* maximum allowed limits.
*
* @param angle The new angle.
* @param velocity The new angular velocity.
*/
void SetState(units::radian_t angle, units::radians_per_second_t velocity);
/**
* Returns whether the arm would hit the lower limit.
*
* @param armAngle The arm height.
* @return Whether the arm would hit the lower limit.
*/
bool WouldHitLowerLimit(units::radian_t armAngle) const;
/**
* Returns whether the arm would hit the upper limit.
*
* @param armAngle The arm height.
* @return Whether the arm would hit the upper limit.
*/
bool WouldHitUpperLimit(units::radian_t armAngle) const;
/**
* Returns whether the arm has hit the lower limit.
*
* @return Whether the arm has hit the lower limit.
*/
bool HasHitLowerLimit() const;
/**
* Returns whether the arm has hit the upper limit.
*
* @return Whether the arm has hit the upper limit.
*/
bool HasHitUpperLimit() const;
/**
* Returns the current arm angle.
*
* @return The current arm angle.
*/
units::radian_t GetAngle() const;
/**
* Returns the current arm velocity.
*
* @return The current arm velocity.
*/
units::radians_per_second_t GetVelocity() const;
/**
* Returns the arm current draw.
*
* @return The arm current draw.
*/
units::ampere_t GetCurrentDraw() const;
/**
* Sets the input voltage for the arm.
*
* @param voltage The input voltage.
*/
void SetInputVoltage(units::volt_t voltage);
/**
* Calculates a rough estimate of the moment of inertia of an arm given its
* length and mass.
*
* @param length The length of the arm.
* @param mass The mass of the arm.
*
* @return The calculated moment of inertia.
*/
static constexpr units::kilogram_square_meter_t EstimateMOI(
units::meter_t length, units::kilogram_t mass) {
return 1.0 / 3.0 * mass * length * length;
}
protected:
/**
* Updates the state estimate of the arm.
*
* @param currentXhat The current state estimate.
* @param u The system inputs (voltage).
* @param dt The time difference between controller updates.
*/
Vectord<2> UpdateX(const Vectord<2>& currentXhat, const Vectord<1>& u,
units::second_t dt) override;
private:
units::meter_t m_armLen;
units::radian_t m_minAngle;
units::radian_t m_maxAngle;
const DCMotor m_gearbox;
double m_gearing;
bool m_simulateGravity;
};
} // namespace frc::sim

View File

@@ -0,0 +1,44 @@
// 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.
#pragma once
#include <memory>
#include "frc/PneumaticsModuleType.h"
#include "frc/simulation/PneumaticsBaseSim.h"
namespace frc::sim {
class SolenoidSim {
public:
SolenoidSim(std::shared_ptr<PneumaticsBaseSim> moduleSim, int channel);
SolenoidSim(int module, PneumaticsModuleType type, int channel);
SolenoidSim(PneumaticsModuleType type, int channel);
~SolenoidSim() = default;
bool GetOutput() const;
void SetOutput(bool output);
/**
* Register a callback to be run when the output of this solenoid has changed.
*
* @param callback the callback
* @param initialNotify whether to run the callback with the initial state
* @return the {@link CallbackStore} object associated with this callback.
* Save a reference to this object; it being deconstructed cancels the
* callback.
*/
[[nodiscard]]
std::unique_ptr<CallbackStore> RegisterOutputCallback(NotifyCallback callback,
bool initialNotify);
std::shared_ptr<PneumaticsBaseSim> GetModuleSim() const;
private:
std::shared_ptr<PneumaticsBaseSim> m_module;
int m_channel;
};
} // namespace frc::sim