Major formatting changes (breaks diffs). No code changes.

The changes made in this commit do not affect any actual code,
    they are purely aesthetic. I ran clang-format with google style
    over all .h/.cpp files in wpilibc that weren't in wpilibC++Sim
    or gtest, and the eclipse formatter over all of the Java files
    using the Google eclipse formatting configuration.

Change-Id: I9627bca0bc103c398ecc1c5ba17467193291ae63
This commit is contained in:
James Kuszmaul
2015-06-25 15:07:55 -04:00
parent bd64d9a7ef
commit 7eb8550bdb
470 changed files with 89798 additions and 77287 deletions

View File

@@ -16,4 +16,3 @@
#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
TypeName(const TypeName&); \
void operator=(const TypeName&)

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -18,18 +19,19 @@
*
* This class represents a subclass of Trigger that is specifically aimed at
* buttons on an operator interface as a common use case of the more generalized
* Trigger objects. This is a simple wrapper around Trigger with the method names
* Trigger objects. This is a simple wrapper around Trigger with the method
* names
* renamed to fit the Button object use.
*
*
* @author brad
*/
class Button : public Trigger {
public:
virtual void WhenPressed(Command *command);
virtual void WhileHeld(Command *command);
virtual void WhenReleased(Command *command);
virtual void CancelWhenPressed(Command *command);
virtual void ToggleWhenPressed(Command *command);
public:
virtual void WhenPressed(Command *command);
virtual void WhileHeld(Command *command);
virtual void WhenReleased(Command *command);
virtual void CancelWhenPressed(Command *command);
virtual void ToggleWhenPressed(Command *command);
};
#endif

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -10,18 +11,17 @@
class Trigger;
class Command;
class ButtonScheduler
{
public:
ButtonScheduler(bool last, Trigger *button, Command *orders);
virtual ~ButtonScheduler() {}
virtual void Execute() = 0;
void Start();
class ButtonScheduler {
public:
ButtonScheduler(bool last, Trigger *button, Command *orders);
virtual ~ButtonScheduler() {}
virtual void Execute() = 0;
void Start();
protected:
bool m_pressedLast;
Trigger *m_button;
Command *m_command;
protected:
bool m_pressedLast;
Trigger *m_button;
Command *m_command;
};
#endif

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -12,14 +13,14 @@
class Trigger;
class Command;
class CancelButtonScheduler : public ButtonScheduler
{
public:
CancelButtonScheduler(bool last, Trigger *button, Command *orders);
virtual ~CancelButtonScheduler() {}
virtual void Execute();
private:
bool pressedLast;
class CancelButtonScheduler : public ButtonScheduler {
public:
CancelButtonScheduler(bool last, Trigger *button, Command *orders);
virtual ~CancelButtonScheduler() {}
virtual void Execute();
private:
bool pressedLast;
};
#endif

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -12,12 +13,11 @@
class Trigger;
class Command;
class HeldButtonScheduler : public ButtonScheduler
{
public:
HeldButtonScheduler(bool last, Trigger *button, Command *orders);
virtual ~HeldButtonScheduler() {}
virtual void Execute();
class HeldButtonScheduler : public ButtonScheduler {
public:
HeldButtonScheduler(bool last, Trigger *button, Command *orders);
virtual ~HeldButtonScheduler() {}
virtual void Execute();
};
#endif

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -9,21 +10,20 @@
#include "Buttons/Button.h"
class InternalButton : public Button
{
public:
InternalButton();
InternalButton(bool inverted);
virtual ~InternalButton() {}
class InternalButton : public Button {
public:
InternalButton();
InternalButton(bool inverted);
virtual ~InternalButton() {}
void SetInverted(bool inverted);
void SetPressed(bool pressed);
void SetInverted(bool inverted);
void SetPressed(bool pressed);
virtual bool Get();
virtual bool Get();
private:
bool m_pressed;
bool m_inverted;
private:
bool m_pressed;
bool m_inverted;
};
#endif

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -10,17 +11,16 @@
#include "GenericHID.h"
#include "Buttons/Button.h"
class JoystickButton : public Button
{
public:
JoystickButton(GenericHID *joystick, int buttonNumber);
virtual ~JoystickButton() {}
class JoystickButton : public Button {
public:
JoystickButton(GenericHID *joystick, int buttonNumber);
virtual ~JoystickButton() {}
virtual bool Get();
virtual bool Get();
private:
GenericHID *m_joystick;
int m_buttonNumber;
private:
GenericHID *m_joystick;
int m_buttonNumber;
};
#endif

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -10,19 +11,17 @@
#include "Buttons/Button.h"
#include <string>
class NetworkButton : public Button
{
public:
NetworkButton(const char *tableName, const char *field);
NetworkButton(ITable* table, const char *field);
virtual ~NetworkButton() {}
class NetworkButton : public Button {
public:
NetworkButton(const char *tableName, const char *field);
NetworkButton(ITable *table, const char *field);
virtual ~NetworkButton() {}
virtual bool Get();
private:
ITable* m_netTable;
std::string m_field;
virtual bool Get();
private:
ITable *m_netTable;
std::string m_field;
};
#endif

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -12,12 +13,11 @@
class Trigger;
class Command;
class PressedButtonScheduler : public ButtonScheduler
{
public:
PressedButtonScheduler(bool last, Trigger *button, Command *orders);
virtual ~PressedButtonScheduler() {}
virtual void Execute();
class PressedButtonScheduler : public ButtonScheduler {
public:
PressedButtonScheduler(bool last, Trigger *button, Command *orders);
virtual ~PressedButtonScheduler() {}
virtual void Execute();
};
#endif

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -12,12 +13,11 @@
class Trigger;
class Command;
class ReleasedButtonScheduler : public ButtonScheduler
{
public:
ReleasedButtonScheduler(bool last, Trigger *button, Command *orders);
virtual ~ReleasedButtonScheduler() {}
virtual void Execute();
class ReleasedButtonScheduler : public ButtonScheduler {
public:
ReleasedButtonScheduler(bool last, Trigger *button, Command *orders);
virtual ~ReleasedButtonScheduler() {}
virtual void Execute();
};
#endif

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -12,14 +13,14 @@
class Trigger;
class Command;
class ToggleButtonScheduler : public ButtonScheduler
{
public:
ToggleButtonScheduler(bool last, Trigger *button, Command *orders);
virtual ~ToggleButtonScheduler() {}
virtual void Execute();
private:
bool pressedLast;
class ToggleButtonScheduler : public ButtonScheduler {
public:
ToggleButtonScheduler(bool last, Trigger *button, Command *orders);
virtual ~ToggleButtonScheduler() {}
virtual void Execute();
private:
bool pressedLast;
};
#endif

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -15,35 +16,37 @@ class Command;
* This class provides an easy way to link commands to inputs.
*
* It is very easy to link a polled input to a command. For instance, you could
* link the trigger button of a joystick to a "score" command or an encoder reaching
* link the trigger button of a joystick to a "score" command or an encoder
* reaching
* a particular value.
*
* It is encouraged that teams write a subclass of Trigger if they want to have
* something unusual (for instance, if they want to react to the user holding
* a button while the robot is reading a certain sensor input). For this, they
* only have to write the {@link Trigger#Get()} method to get the full functionality
* only have to write the {@link Trigger#Get()} method to get the full
* functionality
* of the Trigger class.
*
* @author Brad Miller, Joe Grinstead
*/
class Trigger : public Sendable
{
public:
Trigger();
virtual ~Trigger() {}
bool Grab();
virtual bool Get() = 0;
void WhenActive(Command *command);
void WhileActive(Command *command);
void WhenInactive(Command *command);
void CancelWhenActive(Command *command);
void ToggleWhenActive(Command *command);
virtual void InitTable(ITable* table);
virtual ITable* GetTable() const;
virtual std::string GetSmartDashboardType() const;
protected:
ITable* m_table;
class Trigger : public Sendable {
public:
Trigger();
virtual ~Trigger() {}
bool Grab();
virtual bool Get() = 0;
void WhenActive(Command *command);
void WhileActive(Command *command);
void WhenInactive(Command *command);
void CancelWhenActive(Command *command);
void ToggleWhenActive(Command *command);
virtual void InitTable(ITable *table);
virtual ITable *GetTable() const;
virtual std::string GetSmartDashboardType() const;
protected:
ITable *m_table;
};
#endif

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -18,147 +19,160 @@ class Subsystem;
/**
* The Command class is at the very core of the entire command framework.
* Every command can be started with a call to {@link Command#Start() Start()}.
* Once a command is started it will call {@link Command#Initialize() Initialize()}, and then
* will repeatedly call {@link Command#Execute() Execute()} until the {@link Command#IsFinished() IsFinished()}
* Once a command is started it will call {@link Command#Initialize()
* Initialize()}, and then
* will repeatedly call {@link Command#Execute() Execute()} until the {@link
*Command#IsFinished() IsFinished()}
* returns true. Once it does, {@link Command#End() End()} will be called.
*
* <p>However, if at any point while it is running {@link Command#Cancel() Cancel()} is called, then
* the command will be stopped and {@link Command#Interrupted() Interrupted()} will be called.</p>
* <p>However, if at any point while it is running {@link Command#Cancel()
* Cancel()} is called, then
* the command will be stopped and {@link Command#Interrupted() Interrupted()}
* will be called.</p>
*
* <p>If a command uses a {@link Subsystem}, then it should specify that it does so by
* <p>If a command uses a {@link Subsystem}, then it should specify that it does
* so by
* calling the {@link Command#Requires(Subsystem) Requires(...)} method
* in its constructor. Note that a Command may have multiple requirements, and
* {@link Command#Requires(Subsystem) Requires(...)} should be
* called for each one.</p>
*
* <p>If a command is running and a new command with shared requirements is started,
* <p>If a command is running and a new command with shared requirements is
* started,
* then one of two things will happen. If the active command is interruptible,
* then {@link Command#Cancel() Cancel()} will be called and the command will be removed
* then {@link Command#Cancel() Cancel()} will be called and the command will be
* removed
* to make way for the new one. If the active command is not interruptible, the
* other one will not even be started, and the active one will continue functioning.</p>
* other one will not even be started, and the active one will continue
* functioning.</p>
*
* @see CommandGroup
* @see Subsystem
*/
class Command : public ErrorBase, public NamedSendable, public ITableListener
{
friend class CommandGroup;
friend class Scheduler;
public:
Command();
Command(const char *name);
Command(double timeout);
Command(const char *name, double timeout);
virtual ~Command();
double TimeSinceInitialized() const;
void Requires(Subsystem *s);
bool IsCanceled() const;
void Start();
bool Run();
void Cancel();
bool IsRunning() const;
bool IsInterruptible() const;
void SetInterruptible(bool interruptible);
bool DoesRequire(Subsystem *subsystem) const;
typedef std::set<Subsystem *> SubsystemSet;
SubsystemSet GetRequirements() const;
CommandGroup *GetGroup() const;
void SetRunWhenDisabled(bool run);
bool WillRunWhenDisabled() const;
int GetID() const;
class Command : public ErrorBase, public NamedSendable, public ITableListener {
friend class CommandGroup;
friend class Scheduler;
public:
Command();
Command(const char *name);
Command(double timeout);
Command(const char *name, double timeout);
virtual ~Command();
double TimeSinceInitialized() const;
void Requires(Subsystem *s);
bool IsCanceled() const;
void Start();
bool Run();
void Cancel();
bool IsRunning() const;
bool IsInterruptible() const;
void SetInterruptible(bool interruptible);
bool DoesRequire(Subsystem *subsystem) const;
typedef std::set<Subsystem *> SubsystemSet;
SubsystemSet GetRequirements() const;
CommandGroup *GetGroup() const;
void SetRunWhenDisabled(bool run);
bool WillRunWhenDisabled() const;
int GetID() const;
protected:
void SetTimeout(double timeout);
bool IsTimedOut() const;
bool AssertUnlocked(const char *message);
void SetParent(CommandGroup *parent);
/**
* The initialize method is called the first time this Command is run after
* being started.
*/
virtual void Initialize() = 0;
/**
* The execute method is called repeatedly until this Command either finishes
* or is canceled.
*/
virtual void Execute() = 0;
/**
* Returns whether this command is finished.
* If it is, then the command will be removed
* and {@link Command#end() end()} will be called.
*
* <p>It may be useful for a team to reference the {@link Command#isTimedOut() isTimedOut()} method
* for time-sensitive commands.</p>
* @return whether this command is finished.
* @see Command#isTimedOut() isTimedOut()
*/
virtual bool IsFinished() = 0;
/**
* Called when the command ended peacefully. This is where you may want
* to wrap up loose ends, like shutting off a motor that was being used
* in the command.
*/
virtual void End() = 0;
/**
* Called when the command ends because somebody called {@link Command#cancel() cancel()}
* or another command shared the same requirements as this one, and booted
* it out.
*
* <p>This is where you may want
* to wrap up loose ends, like shutting off a motor that was being used
* in the command.</p>
*
* <p>Generally, it is useful to simply call the {@link Command#end() end()} method
* within this method</p>
*/
virtual void Interrupted() = 0;
virtual void _Initialize();
virtual void _Interrupted();
virtual void _Execute();
virtual void _End();
virtual void _Cancel();
protected:
void SetTimeout(double timeout);
bool IsTimedOut() const;
bool AssertUnlocked(const char *message);
void SetParent(CommandGroup *parent);
/**
* The initialize method is called the first time this Command is run after
* being started.
*/
virtual void Initialize() = 0;
/**
* The execute method is called repeatedly until this Command either finishes
* or is canceled.
*/
virtual void Execute() = 0;
/**
* Returns whether this command is finished.
* If it is, then the command will be removed
* and {@link Command#end() end()} will be called.
*
* <p>It may be useful for a team to reference the {@link Command#isTimedOut()
* isTimedOut()} method
* for time-sensitive commands.</p>
* @return whether this command is finished.
* @see Command#isTimedOut() isTimedOut()
*/
virtual bool IsFinished() = 0;
/**
* Called when the command ended peacefully. This is where you may want
* to wrap up loose ends, like shutting off a motor that was being used
* in the command.
*/
virtual void End() = 0;
/**
* Called when the command ends because somebody called {@link
*Command#cancel() cancel()}
* or another command shared the same requirements as this one, and booted
* it out.
*
* <p>This is where you may want
* to wrap up loose ends, like shutting off a motor that was being used
* in the command.</p>
*
* <p>Generally, it is useful to simply call the {@link Command#end() end()}
* method
* within this method</p>
*/
virtual void Interrupted() = 0;
virtual void _Initialize();
virtual void _Interrupted();
virtual void _Execute();
virtual void _End();
virtual void _Cancel();
private:
void InitCommand(const char *name, double timeout);
void LockChanges();
/*synchronized*/ void Removed();
void StartRunning();
void StartTiming();
private:
void InitCommand(const char *name, double timeout);
void LockChanges();
/*synchronized*/ void Removed();
void StartRunning();
void StartTiming();
/** The name of this command */
std::string m_name;
/** The time since this command was initialized */
double m_startTime;
/** The time (in seconds) before this command "times out" (or -1 if no timeout) */
double m_timeout;
/** Whether or not this command has been initialized */
bool m_initialized;
/** The requirements (or null if no requirements) */
SubsystemSet m_requirements;
/** Whether or not it is running */
bool m_running;
/** Whether or not it is interruptible*/
bool m_interruptible;
/** Whether or not it has been canceled */
bool m_canceled;
/** Whether or not it has been locked */
bool m_locked;
/** Whether this command should run when the robot is disabled */
bool m_runWhenDisabled;
/** The {@link CommandGroup} this is in */
CommandGroup *m_parent;
int m_commandID;
static int m_commandCounter;
public:
virtual std::string GetName();
virtual void InitTable(ITable* table);
virtual ITable* GetTable() const;
virtual std::string GetSmartDashboardType() const;
virtual void ValueChanged(ITable* source, const std::string& key, EntryValue value, bool isNew);
protected:
ITable* m_table;
/** The name of this command */
std::string m_name;
/** The time since this command was initialized */
double m_startTime;
/** The time (in seconds) before this command "times out" (or -1 if no
* timeout) */
double m_timeout;
/** Whether or not this command has been initialized */
bool m_initialized;
/** The requirements (or null if no requirements) */
SubsystemSet m_requirements;
/** Whether or not it is running */
bool m_running;
/** Whether or not it is interruptible*/
bool m_interruptible;
/** Whether or not it has been canceled */
bool m_canceled;
/** Whether or not it has been locked */
bool m_locked;
/** Whether this command should run when the robot is disabled */
bool m_runWhenDisabled;
/** The {@link CommandGroup} this is in */
CommandGroup *m_parent;
int m_commandID;
static int m_commandCounter;
public:
virtual std::string GetName();
virtual void InitTable(ITable *table);
virtual ITable *GetTable() const;
virtual std::string GetSmartDashboardType() const;
virtual void ValueChanged(ITable *source, const std::string &key,
EntryValue value, bool isNew);
protected:
ITable *m_table;
};
#endif

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -15,57 +16,59 @@
/**
* A {@link CommandGroup} is a list of commands which are executed in sequence.
*
* <p>Commands in a {@link CommandGroup} are added using the {@link CommandGroup#AddSequential(Command) AddSequential(...)} method
* <p>Commands in a {@link CommandGroup} are added using the {@link
* CommandGroup#AddSequential(Command) AddSequential(...)} method
* and are called sequentially.
* {@link CommandGroup CommandGroups} are themselves {@link Command Commands}
* and can be given to other {@link CommandGroup CommandGroups}.</p>
*
* <p>{@link CommandGroup CommandGroups} will carry all of the requirements of their {@link Command subcommands}. Additional
* requirements can be specified by calling {@link CommandGroup#Requires(Subsystem) Requires(...)}
* <p>{@link CommandGroup CommandGroups} will carry all of the requirements of
* their {@link Command subcommands}. Additional
* requirements can be specified by calling {@link
*CommandGroup#Requires(Subsystem) Requires(...)}
* normally in the constructor.</P>
*
* <p>CommandGroups can also execute commands in parallel, simply by adding them
* using {@link CommandGroup#AddParallel(Command) AddParallel(...)}.</p>
*
*
* @see Command
* @see Subsystem
*/
class CommandGroup : public Command
{
public:
CommandGroup();
CommandGroup(const char *name);
virtual ~CommandGroup();
void AddSequential(Command *command);
void AddSequential(Command *command, double timeout);
void AddParallel(Command *command);
void AddParallel(Command *command, double timeout);
bool IsInterruptible() const;
int GetSize() const;
class CommandGroup : public Command {
public:
CommandGroup();
CommandGroup(const char *name);
virtual ~CommandGroup();
protected:
virtual void Initialize();
virtual void Execute();
virtual bool IsFinished();
virtual void End();
virtual void Interrupted();
virtual void _Initialize();
virtual void _Interrupted();
virtual void _Execute();
virtual void _End();
void AddSequential(Command *command);
void AddSequential(Command *command, double timeout);
void AddParallel(Command *command);
void AddParallel(Command *command, double timeout);
bool IsInterruptible() const;
int GetSize() const;
private:
void CancelConflicts(Command *command);
protected:
virtual void Initialize();
virtual void Execute();
virtual bool IsFinished();
virtual void End();
virtual void Interrupted();
virtual void _Initialize();
virtual void _Interrupted();
virtual void _Execute();
virtual void _End();
typedef std::vector<CommandGroupEntry> CommandVector;
/** The commands in this group (stored in entries) */
CommandVector m_commands;
typedef std::list<CommandGroupEntry> CommandList;
/** The active children in this group (stored in entries) */
CommandList m_children;
/** The current command, -1 signifies that none have been run */
int m_currentCommandIndex;
private:
void CancelConflicts(Command *command);
typedef std::vector<CommandGroupEntry> CommandVector;
/** The commands in this group (stored in entries) */
CommandVector m_commands;
typedef std::list<CommandGroupEntry> CommandList;
/** The active children in this group (stored in entries) */
CommandList m_children;
/** The current command, -1 signifies that none have been run */
int m_currentCommandIndex;
};
#endif

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -9,19 +10,22 @@
class Command;
class CommandGroupEntry
{
public:
typedef enum {kSequence_InSequence, kSequence_BranchPeer, kSequence_BranchChild} Sequence;
class CommandGroupEntry {
public:
typedef enum {
kSequence_InSequence,
kSequence_BranchPeer,
kSequence_BranchChild
} Sequence;
CommandGroupEntry();
CommandGroupEntry(Command *command, Sequence state);
CommandGroupEntry(Command *command, Sequence state, double timeout);
bool IsTimedOut() const;
CommandGroupEntry();
CommandGroupEntry(Command *command, Sequence state);
CommandGroupEntry(Command *command, Sequence state, double timeout);
bool IsTimedOut() const;
double m_timeout;
Command *m_command;
Sequence m_state;
double m_timeout;
Command *m_command;
Sequence m_state;
};
#endif

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -13,44 +14,44 @@
class PIDController;
class PIDCommand : public Command, public PIDOutput, public PIDSource
{
public:
PIDCommand(const char *name, double p, double i, double d);
PIDCommand(const char *name, double p, double i, double d, double period);
PIDCommand(const char *name, double p, double i, double d, double f, double perioid);
PIDCommand(double p, double i, double d);
PIDCommand(double p, double i, double d, double period);
PIDCommand(double p, double i, double d, double f, double period);
virtual ~PIDCommand();
void SetSetpointRelative(double deltaSetpoint);
class PIDCommand : public Command, public PIDOutput, public PIDSource {
public:
PIDCommand(const char *name, double p, double i, double d);
PIDCommand(const char *name, double p, double i, double d, double period);
PIDCommand(const char *name, double p, double i, double d, double f,
double perioid);
PIDCommand(double p, double i, double d);
PIDCommand(double p, double i, double d, double period);
PIDCommand(double p, double i, double d, double f, double period);
virtual ~PIDCommand();
// PIDOutput interface
virtual void PIDWrite(float output);
void SetSetpointRelative(double deltaSetpoint);
// PIDSource interface
virtual double PIDGet() const;
protected:
PIDController *GetPIDController() const;
virtual void _Initialize();
virtual void _Interrupted();
virtual void _End();
void SetSetpoint(double setpoint);
double GetSetpoint() const;
double GetPosition() const;
// PIDOutput interface
virtual void PIDWrite(float output);
virtual double ReturnPIDInput() const = 0;
virtual void UsePIDOutput(double output) = 0;
// PIDSource interface
virtual double PIDGet() const;
private:
/** The internal {@link PIDController} */
PIDController *m_controller;
protected:
PIDController *GetPIDController() const;
virtual void _Initialize();
virtual void _Interrupted();
virtual void _End();
void SetSetpoint(double setpoint);
double GetSetpoint() const;
double GetPosition() const;
public:
virtual void InitTable(ITable* table);
virtual std::string GetSmartDashboardType() const;
virtual double ReturnPIDInput() const = 0;
virtual void UsePIDOutput(double output) = 0;
private:
/** The internal {@link PIDController} */
PIDController *m_controller;
public:
virtual void InitTable(ITable *table);
virtual std::string GetSmartDashboardType() const;
};
#endif

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -17,54 +18,56 @@
* which uses a single {@link PIDController} almost constantly (for instance,
* an elevator which attempts to stay at a constant height).
*
* <p>It provides some convenience methods to run an internal {@link PIDController}.
* It also allows access to the internal {@link PIDController} in order to give total control
* <p>It provides some convenience methods to run an internal {@link
* PIDController}.
* It also allows access to the internal {@link PIDController} in order to give
* total control
* to the programmer.</p>
*
*/
class PIDSubsystem : public Subsystem, public PIDOutput, public PIDSource
{
public:
PIDSubsystem(const char *name, double p, double i, double d);
PIDSubsystem(const char *name, double p, double i, double d, double f);
PIDSubsystem(const char *name, double p, double i, double d, double f, double period);
PIDSubsystem(double p, double i, double d);
PIDSubsystem(double p, double i, double d, double f);
PIDSubsystem(double p, double i, double d, double f, double period);
virtual ~PIDSubsystem();
class PIDSubsystem : public Subsystem, public PIDOutput, public PIDSource {
public:
PIDSubsystem(const char *name, double p, double i, double d);
PIDSubsystem(const char *name, double p, double i, double d, double f);
PIDSubsystem(const char *name, double p, double i, double d, double f,
double period);
PIDSubsystem(double p, double i, double d);
PIDSubsystem(double p, double i, double d, double f);
PIDSubsystem(double p, double i, double d, double f, double period);
virtual ~PIDSubsystem();
void Enable();
void Disable();
void Enable();
void Disable();
// PIDOutput interface
virtual void PIDWrite(float output);
// PIDOutput interface
virtual void PIDWrite(float output);
// PIDSource interface
virtual double PIDGet() const;
void SetSetpoint(double setpoint);
void SetSetpointRelative(double deltaSetpoint);
void SetInputRange(float minimumInput, float maximumInput);
void SetOutputRange(float minimumOutput, float maximumOutput);
double GetSetpoint();
double GetPosition();
// PIDSource interface
virtual double PIDGet() const;
void SetSetpoint(double setpoint);
void SetSetpointRelative(double deltaSetpoint);
void SetInputRange(float minimumInput, float maximumInput);
void SetOutputRange(float minimumOutput, float maximumOutput);
double GetSetpoint();
double GetPosition();
virtual void SetAbsoluteTolerance(float absValue);
virtual void SetPercentTolerance(float percent);
virtual bool OnTarget() const;
virtual void SetAbsoluteTolerance(float absValue);
virtual void SetPercentTolerance(float percent);
virtual bool OnTarget() const;
protected:
PIDController *GetPIDController();
protected:
PIDController *GetPIDController();
virtual double ReturnPIDInput() const = 0;
virtual void UsePIDOutput(double output) = 0;
virtual double ReturnPIDInput() const = 0;
virtual void UsePIDOutput(double output) = 0;
private:
/** The internal {@link PIDController} */
PIDController *m_controller;
private:
/** The internal {@link PIDController} */
PIDController *m_controller;
public:
virtual void InitTable(ITable* table);
virtual std::string GetSmartDashboardType() const;
public:
virtual void InitTable(ITable *table);
virtual std::string GetSmartDashboardType() const;
};
#endif

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -10,21 +11,20 @@
#include "Commands/Command.h"
#include <string>
class PrintCommand : public Command
{
public:
PrintCommand(const char *message);
virtual ~PrintCommand() {}
class PrintCommand : public Command {
public:
PrintCommand(const char *message);
virtual ~PrintCommand() {}
protected:
virtual void Initialize();
virtual void Execute();
virtual bool IsFinished();
virtual void End();
virtual void Interrupted();
protected:
virtual void Initialize();
virtual void Execute();
virtual bool IsFinished();
virtual void End();
virtual void Interrupted();
private:
std::string m_message;
private:
std::string m_message;
};
#endif

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -23,50 +24,48 @@
class ButtonScheduler;
class Subsystem;
class Scheduler : public ErrorBase, public NamedSendable
{
public:
static Scheduler *GetInstance();
class Scheduler : public ErrorBase, public NamedSendable {
public:
static Scheduler *GetInstance();
void AddCommand(Command* command);
void AddButton(ButtonScheduler* button);
void RegisterSubsystem(Subsystem *subsystem);
void Run();
void Remove(Command *command);
void RemoveAll();
void ResetAll();
void SetEnabled(bool enabled);
void UpdateTable();
std::string GetSmartDashboardType() const;
void InitTable(ITable *subTable);
ITable * GetTable() const;
std::string GetName();
std::string GetType() const;
void AddCommand(Command *command);
void AddButton(ButtonScheduler *button);
void RegisterSubsystem(Subsystem *subsystem);
void Run();
void Remove(Command *command);
void RemoveAll();
void ResetAll();
void SetEnabled(bool enabled);
private:
Scheduler();
virtual ~Scheduler();
void UpdateTable();
std::string GetSmartDashboardType() const;
void InitTable(ITable *subTable);
ITable *GetTable() const;
std::string GetName();
std::string GetType() const;
void ProcessCommandAddition(Command *command);
private:
Scheduler();
virtual ~Scheduler();
static Scheduler *_instance;
Command::SubsystemSet m_subsystems;
MUTEX_ID m_buttonsLock;
typedef std::vector<ButtonScheduler *> ButtonVector;
ButtonVector m_buttons;
typedef std::vector<Command *> CommandVector;
MUTEX_ID m_additionsLock;
CommandVector m_additions;
typedef std::set<Command *> CommandSet;
CommandSet m_commands;
bool m_adding;
bool m_enabled;
StringArray *commands;
NumberArray *ids;
NumberArray *toCancel;
ITable *m_table;
bool m_runningCommandsChanged;
void ProcessCommandAddition(Command *command);
static Scheduler *_instance;
Command::SubsystemSet m_subsystems;
MUTEX_ID m_buttonsLock;
typedef std::vector<ButtonScheduler *> ButtonVector;
ButtonVector m_buttons;
typedef std::vector<Command *> CommandVector;
MUTEX_ID m_additionsLock;
CommandVector m_additions;
typedef std::set<Command *> CommandSet;
CommandSet m_commands;
bool m_adding;
bool m_enabled;
StringArray *commands;
NumberArray *ids;
NumberArray *toCancel;
ITable *m_table;
bool m_runningCommandsChanged;
};
#endif

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -9,21 +10,20 @@
#include "Commands/Command.h"
class StartCommand : public Command
{
public:
StartCommand(Command *commandToStart);
virtual ~StartCommand() {}
class StartCommand : public Command {
public:
StartCommand(Command *commandToStart);
virtual ~StartCommand() {}
protected:
virtual void Initialize();
virtual void Execute();
virtual bool IsFinished();
virtual void End();
virtual void Interrupted();
protected:
virtual void Initialize();
virtual void Execute();
virtual bool IsFinished();
virtual void End();
virtual void Interrupted();
private:
Command *m_commandToFork;
private:
Command *m_commandToFork;
};
#endif

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -11,38 +12,38 @@
#include "SmartDashboard/NamedSendable.h"
#include <string>
class Command;
class Subsystem : public ErrorBase, public NamedSendable
{
friend class Scheduler;
public:
Subsystem(const char *name);
virtual ~Subsystem() {}
class Subsystem : public ErrorBase, public NamedSendable {
friend class Scheduler;
void SetDefaultCommand(Command *command);
Command *GetDefaultCommand();
void SetCurrentCommand(Command *command);
Command *GetCurrentCommand() const;
virtual void InitDefaultCommand();
private:
void ConfirmCommand();
public:
Subsystem(const char *name);
virtual ~Subsystem() {}
Command *m_currentCommand;
bool m_currentCommandChanged;
Command *m_defaultCommand;
std::string m_name;
bool m_initializedDefaultCommand;
void SetDefaultCommand(Command *command);
Command *GetDefaultCommand();
void SetCurrentCommand(Command *command);
Command *GetCurrentCommand() const;
virtual void InitDefaultCommand();
public:
virtual std::string GetName();
virtual void InitTable(ITable* table);
virtual ITable* GetTable() const;
virtual std::string GetSmartDashboardType() const;
protected:
ITable* m_table;
private:
void ConfirmCommand();
Command *m_currentCommand;
bool m_currentCommandChanged;
Command *m_defaultCommand;
std::string m_name;
bool m_initializedDefaultCommand;
public:
virtual std::string GetName();
virtual void InitTable(ITable *table);
virtual ITable *GetTable() const;
virtual std::string GetSmartDashboardType() const;
protected:
ITable *m_table;
};
#endif

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -9,19 +10,18 @@
#include "Commands/Command.h"
class WaitCommand : public Command
{
public:
WaitCommand(double timeout);
WaitCommand(const char *name, double timeout);
virtual ~WaitCommand() {}
class WaitCommand : public Command {
public:
WaitCommand(double timeout);
WaitCommand(const char *name, double timeout);
virtual ~WaitCommand() {}
protected:
virtual void Initialize();
virtual void Execute();
virtual bool IsFinished();
virtual void End();
virtual void Interrupted();
protected:
virtual void Initialize();
virtual void Execute();
virtual bool IsFinished();
virtual void End();
virtual void Interrupted();
};
#endif

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -9,19 +10,18 @@
#include "Commands/Command.h"
class WaitForChildren : public Command
{
public:
WaitForChildren(double timeout);
WaitForChildren(const char *name, double timeout);
virtual ~WaitForChildren() {}
class WaitForChildren : public Command {
public:
WaitForChildren(double timeout);
WaitForChildren(const char *name, double timeout);
virtual ~WaitForChildren() {}
protected:
virtual void Initialize();
virtual void Execute();
virtual bool IsFinished();
virtual void End();
virtual void Interrupted();
protected:
virtual void Initialize();
virtual void Execute();
virtual bool IsFinished();
virtual void End();
virtual void Interrupted();
};
#endif

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -9,22 +10,21 @@
#include "Commands/Command.h"
class WaitUntilCommand : public Command
{
public:
WaitUntilCommand(double time);
WaitUntilCommand(const char *name, double time);
virtual ~WaitUntilCommand() {}
class WaitUntilCommand : public Command {
public:
WaitUntilCommand(double time);
WaitUntilCommand(const char *name, double time);
virtual ~WaitUntilCommand() {}
protected:
virtual void Initialize();
virtual void Execute();
virtual bool IsFinished();
virtual void End();
virtual void Interrupted();
protected:
virtual void Initialize();
virtual void Execute();
virtual bool IsFinished();
virtual void End();
virtual void Interrupted();
private:
double m_time;
private:
double m_time;
};
#endif

View File

@@ -12,23 +12,24 @@
/**
* Interface for Controllers
* Common interface for controllers. Controllers run control loops, the most common
* are PID controllers and their variants, but this includes anything that is controlling
* Common interface for controllers. Controllers run control loops, the most
* common
* are PID controllers and their variants, but this includes anything that is
* controlling
* an actuator in a separate thread.
*/
class Controller
{
public:
virtual ~Controller() {};
/**
* Allows the control loop to run
*/
virtual void Enable() = 0;
/**
* Stops the control loop from running until explicitly re-enabled by calling enable()
*/
virtual void Disable() = 0;
};
class Controller {
public:
virtual ~Controller(){};
/**
* Allows the control loop to run
*/
virtual void Enable() = 0;
/**
* Stops the control loop from running until explicitly re-enabled by calling
* enable()
*/
virtual void Disable() = 0;
};

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Copyright (c) FIRST 2008. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -15,40 +16,39 @@ class ErrorBase;
/**
* Error object represents a library error.
*/
class Error
{
public:
typedef int32_t Code;
class Error {
public:
typedef int32_t Code;
Error();
~Error();
void Clone(Error &error);
Code GetCode() const;
const char *GetMessage() const;
const char *GetFilename() const;
const char *GetFunction() const;
uint32_t GetLineNumber() const;
const ErrorBase* GetOriginatingObject() const;
double GetTimestamp() const;
void Clear();
void Set(Code code, const char* contextMessage, const char* filename, const char *function,
uint32_t lineNumber, const ErrorBase* originatingObject);
static void EnableSuspendOnError(bool enable)
{
m_suspendOnErrorEnabled = enable;
}
Error();
~Error();
void Clone(Error& error);
Code GetCode() const;
const char* GetMessage() const;
const char* GetFilename() const;
const char* GetFunction() const;
uint32_t GetLineNumber() const;
const ErrorBase* GetOriginatingObject() const;
double GetTimestamp() const;
void Clear();
void Set(Code code, const char* contextMessage, const char* filename,
const char* function, uint32_t lineNumber,
const ErrorBase* originatingObject);
static void EnableSuspendOnError(bool enable) {
m_suspendOnErrorEnabled = enable;
}
private:
void Report();
private:
void Report();
Code m_code;
std::string m_message;
std::string m_filename;
std::string m_function;
uint32_t m_lineNumber;
const ErrorBase* m_originatingObject;
double m_timestamp;
Code m_code;
std::string m_message;
std::string m_filename;
std::string m_function;
uint32_t m_lineNumber;
const ErrorBase* m_originatingObject;
double m_timestamp;
static bool m_suspendOnErrorEnabled;
DISALLOW_COPY_AND_ASSIGN(Error);
static bool m_suspendOnErrorEnabled;
DISALLOW_COPY_AND_ASSIGN(Error);
};

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Copyright (c) FIRST 2008. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -9,56 +10,80 @@
#include "Error.h"
#include "HAL/Semaphore.hpp"
#define wpi_setErrnoErrorWithContext(context) (this->SetErrnoError((context), __FILE__, __FUNCTION__, __LINE__))
#define wpi_setErrnoError() (wpi_setErrnoErrorWithContext(""))
#define wpi_setImaqErrorWithContext(code, context) (this->SetImaqError((code), (context), __FILE__, __FUNCTION__, __LINE__))
#define wpi_setErrorWithContext(code, context) (this->SetError((code), (context), __FILE__, __FUNCTION__, __LINE__))
#define wpi_setError(code) (wpi_setErrorWithContext(code, ""))
#define wpi_setStaticErrorWithContext(object, code, context) (object->SetError((code), (context), __FILE__, __FUNCTION__, __LINE__))
#define wpi_setStaticError(object, code) (wpi_setStaticErrorWithContext(object, code, ""))
#define wpi_setGlobalErrorWithContext(code, context) (ErrorBase::SetGlobalError((code), (context), __FILE__, __FUNCTION__, __LINE__))
#define wpi_setGlobalError(code) (wpi_setGlobalErrorWithContext(code, ""))
#define wpi_setWPIErrorWithContext(error, context) (this->SetWPIError((wpi_error_s_##error), (wpi_error_value_##error), (context), __FILE__, __FUNCTION__, __LINE__))
#define wpi_setWPIError(error) (wpi_setWPIErrorWithContext(error, ""))
#define wpi_setStaticWPIErrorWithContext(object, error, context) (object->SetWPIError((wpi_error_s_##error), (context), __FILE__, __FUNCTION__, __LINE__))
#define wpi_setStaticWPIError(object, error) (wpi_setStaticWPIErrorWithContext(object, error, ""))
#define wpi_setGlobalWPIErrorWithContext(error, context) (ErrorBase::SetGlobalWPIError((wpi_error_s_##error), (context), __FILE__, __FUNCTION__, __LINE__))
#define wpi_setGlobalWPIError(error) (wpi_setGlobalWPIErrorWithContext(error, ""))
#define wpi_setErrnoErrorWithContext(context) \
(this->SetErrnoError((context), __FILE__, __FUNCTION__, __LINE__))
#define wpi_setErrnoError() (wpi_setErrnoErrorWithContext(""))
#define wpi_setImaqErrorWithContext(code, context) \
(this->SetImaqError((code), (context), __FILE__, __FUNCTION__, __LINE__))
#define wpi_setErrorWithContext(code, context) \
(this->SetError((code), (context), __FILE__, __FUNCTION__, __LINE__))
#define wpi_setError(code) (wpi_setErrorWithContext(code, ""))
#define wpi_setStaticErrorWithContext(object, code, context) \
(object->SetError((code), (context), __FILE__, __FUNCTION__, __LINE__))
#define wpi_setStaticError(object, code) \
(wpi_setStaticErrorWithContext(object, code, ""))
#define wpi_setGlobalErrorWithContext(code, context) \
(ErrorBase::SetGlobalError((code), (context), __FILE__, __FUNCTION__, \
__LINE__))
#define wpi_setGlobalError(code) (wpi_setGlobalErrorWithContext(code, ""))
#define wpi_setWPIErrorWithContext(error, context) \
(this->SetWPIError((wpi_error_s_##error), (wpi_error_value_##error), \
(context), __FILE__, __FUNCTION__, __LINE__))
#define wpi_setWPIError(error) (wpi_setWPIErrorWithContext(error, ""))
#define wpi_setStaticWPIErrorWithContext(object, error, context) \
(object->SetWPIError((wpi_error_s_##error), (context), __FILE__, \
__FUNCTION__, __LINE__))
#define wpi_setStaticWPIError(object, error) \
(wpi_setStaticWPIErrorWithContext(object, error, ""))
#define wpi_setGlobalWPIErrorWithContext(error, context) \
(ErrorBase::SetGlobalWPIError((wpi_error_s_##error), (context), __FILE__, \
__FUNCTION__, __LINE__))
#define wpi_setGlobalWPIError(error) \
(wpi_setGlobalWPIErrorWithContext(error, ""))
/**
* Base class for most objects.
* ErrorBase is the base class for most objects since it holds the generated error
* for that object. In addition, there is a single instance of a global error object
* ErrorBase is the base class for most objects since it holds the generated
* error
* for that object. In addition, there is a single instance of a global error
* object
*/
class ErrorBase
{
//TODO: Consider initializing instance variables and cleanup in destructor
public:
virtual ~ErrorBase();
virtual Error& GetError();
virtual const Error& GetError() const;
virtual void SetErrnoError(const char *contextMessage, const char* filename,
const char* function, uint32_t lineNumber) const;
virtual void SetImaqError(int success, const char *contextMessage, const char* filename,
const char* function, uint32_t lineNumber) const;
virtual void SetError(Error::Code code, const char *contextMessage, const char* filename,
const char* function, uint32_t lineNumber) const;
virtual void SetWPIError(const char *errorMessage, Error::Code code, const char *contextMessage,
const char* filename, const char* function, uint32_t lineNumber) const;
virtual void CloneError(ErrorBase *rhs) const;
virtual void ClearError() const;
virtual bool StatusIsFatal() const;
static void SetGlobalError(Error::Code code, const char *contextMessage, const char* filename,
const char* function, uint32_t lineNumber);
static void SetGlobalWPIError(const char *errorMessage, const char *contextMessage,
const char* filename, const char* function, uint32_t lineNumber);
static Error& GetGlobalError();
protected:
mutable Error m_error;
// TODO: Replace globalError with a global list of all errors.
static MUTEX_ID _globalErrorMutex;
static Error _globalError;
ErrorBase();
private:
DISALLOW_COPY_AND_ASSIGN(ErrorBase);
class ErrorBase {
// TODO: Consider initializing instance variables and cleanup in destructor
public:
virtual ~ErrorBase();
virtual Error& GetError();
virtual const Error& GetError() const;
virtual void SetErrnoError(const char* contextMessage, const char* filename,
const char* function, uint32_t lineNumber) const;
virtual void SetImaqError(int success, const char* contextMessage,
const char* filename, const char* function,
uint32_t lineNumber) const;
virtual void SetError(Error::Code code, const char* contextMessage,
const char* filename, const char* function,
uint32_t lineNumber) const;
virtual void SetWPIError(const char* errorMessage, Error::Code code,
const char* contextMessage, const char* filename,
const char* function, uint32_t lineNumber) const;
virtual void CloneError(ErrorBase* rhs) const;
virtual void ClearError() const;
virtual bool StatusIsFatal() const;
static void SetGlobalError(Error::Code code, const char* contextMessage,
const char* filename, const char* function,
uint32_t lineNumber);
static void SetGlobalWPIError(const char* errorMessage,
const char* contextMessage,
const char* filename, const char* function,
uint32_t lineNumber);
static Error& GetGlobalError();
protected:
mutable Error m_error;
// TODO: Replace globalError with a global list of all errors.
static MUTEX_ID _globalErrorMutex;
static Error _globalError;
ErrorBase();
private:
DISALLOW_COPY_AND_ASSIGN(ErrorBase);
};

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Copyright (c) FIRST 2008. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -9,30 +10,23 @@
/** GenericHID Interface
*/
class GenericHID
{
public:
enum JoystickHand
{
kLeftHand = 0,
kRightHand = 1
};
class GenericHID {
public:
enum JoystickHand { kLeftHand = 0, kRightHand = 1 };
virtual ~GenericHID()
{
}
virtual ~GenericHID() {}
virtual float GetX(JoystickHand hand = kRightHand) const = 0;
virtual float GetY(JoystickHand hand = kRightHand) const = 0;
virtual float GetZ() const = 0;
virtual float GetTwist() const = 0;
virtual float GetThrottle() const = 0;
virtual float GetRawAxis(uint32_t axis) const = 0;
virtual float GetX(JoystickHand hand = kRightHand) const = 0;
virtual float GetY(JoystickHand hand = kRightHand) const = 0;
virtual float GetZ() const = 0;
virtual float GetTwist() const = 0;
virtual float GetThrottle() const = 0;
virtual float GetRawAxis(uint32_t axis) const = 0;
virtual bool GetTrigger(JoystickHand hand = kRightHand) const = 0;
virtual bool GetTop(JoystickHand hand = kRightHand) const = 0;
virtual bool GetBumper(JoystickHand hand = kRightHand) const = 0;
virtual bool GetRawButton(uint32_t button) const = 0;
virtual bool GetTrigger(JoystickHand hand = kRightHand) const = 0;
virtual bool GetTop(JoystickHand hand = kRightHand) const = 0;
virtual bool GetBumper(JoystickHand hand = kRightHand) const = 0;
virtual bool GetRawButton(uint32_t button) const = 0;
virtual int GetPOV(uint32_t pov = 0) const = 0;
virtual int GetPOV(uint32_t pov = 0) const = 0;
};

View File

@@ -5,21 +5,19 @@
/*----------------------------------------------------------------------------*/
#pragma once
class HLUsageReportingInterface
{
public:
virtual ~HLUsageReportingInterface() {};
virtual void ReportScheduler() = 0;
virtual void ReportSmartDashboard() = 0;
class HLUsageReportingInterface {
public:
virtual ~HLUsageReportingInterface(){};
virtual void ReportScheduler() = 0;
virtual void ReportSmartDashboard() = 0;
};
class HLUsageReporting
{
private:
static HLUsageReportingInterface* impl;
public:
static void SetImplementation(HLUsageReportingInterface* i);
static void ReportScheduler();
static void ReportSmartDashboard();
class HLUsageReporting {
private:
static HLUsageReportingInterface* impl;
public:
static void SetImplementation(HLUsageReportingInterface* i);
static void ReportScheduler();
static void ReportSmartDashboard();
};

View File

@@ -7,60 +7,62 @@
#include <vector>
#include <map>
struct LiveWindowComponent
{
std::string subsystem;
std::string name;
bool isSensor;
struct LiveWindowComponent {
std::string subsystem;
std::string name;
bool isSensor;
LiveWindowComponent()
{}
LiveWindowComponent(std::string subsystem, std::string name, bool isSensor)
{
this->subsystem = subsystem;
this->name = name;
this->isSensor = isSensor;
}
LiveWindowComponent() {}
LiveWindowComponent(std::string subsystem, std::string name, bool isSensor) {
this->subsystem = subsystem;
this->name = name;
this->isSensor = isSensor;
}
};
/**
* The LiveWindow class is the public interface for putting sensors and actuators
* The LiveWindow class is the public interface for putting sensors and
* actuators
* on the LiveWindow.
*
* @author Brad Miller
*/
class LiveWindow {
public:
static LiveWindow * GetInstance();
void Run();
void AddSensor(const char *subsystem, const char *name, LiveWindowSendable *component);
void AddActuator(const char *subsystem, const char *name, LiveWindowSendable *component);
void AddSensor(std::string type, int channel, LiveWindowSendable *component);
void AddActuator(std::string type, int channel, LiveWindowSendable *component);
void AddActuator(std::string type, int module, int channel, LiveWindowSendable *component);
public:
static LiveWindow *GetInstance();
void Run();
void AddSensor(const char *subsystem, const char *name,
LiveWindowSendable *component);
void AddActuator(const char *subsystem, const char *name,
LiveWindowSendable *component);
void AddSensor(std::string type, int channel, LiveWindowSendable *component);
void AddActuator(std::string type, int channel,
LiveWindowSendable *component);
void AddActuator(std::string type, int module, int channel,
LiveWindowSendable *component);
bool IsEnabled() const { return m_enabled; }
void SetEnabled(bool enabled);
bool IsEnabled() const { return m_enabled; }
void SetEnabled(bool enabled);
protected:
LiveWindow();
virtual ~LiveWindow();
protected:
LiveWindow();
virtual ~LiveWindow();
private:
void UpdateValues();
void Initialize();
void InitializeLiveWindowComponents();
private:
void UpdateValues();
void Initialize();
void InitializeLiveWindowComponents();
std::vector<LiveWindowSendable *> m_sensors;
std::map<LiveWindowSendable *, LiveWindowComponent> m_components;
std::vector<LiveWindowSendable *> m_sensors;
std::map<LiveWindowSendable *, LiveWindowComponent> m_components;
ITable *m_liveWindowTable;
ITable *m_statusTable;
ITable *m_liveWindowTable;
ITable *m_statusTable;
Scheduler *m_scheduler;
Scheduler *m_scheduler;
bool m_enabled;
bool m_firstTime;
bool m_enabled;
bool m_firstTime;
};
#endif

View File

@@ -1,5 +1,5 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) Patrick Plenefisch 2012. All Rights Reserved. */
/* Copyright (c) Patrick Plenefisch 2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -14,27 +14,25 @@
*
* @author Patrick Plenefisch
*/
class LiveWindowSendable: public Sendable
{
public:
/**
* Update the table for this sendable object with the latest
* values.
*/
virtual void UpdateTable() = 0;
class LiveWindowSendable : public Sendable {
public:
/**
* Update the table for this sendable object with the latest
* values.
*/
virtual void UpdateTable() = 0;
/**
* Start having this sendable object automatically respond to
* value changes reflect the value on the table.
*/
virtual void StartLiveWindowMode() = 0;
/**
* Start having this sendable object automatically respond to
* value changes reflect the value on the table.
*/
virtual void StartLiveWindowMode() = 0;
/**
* Stop having this sendable object automatically respond to value
* changes.
*/
virtual void StopLiveWindowMode() = 0;
/**
* Stop having this sendable object automatically respond to value
* changes.
*/
virtual void StopLiveWindowMode() = 0;
};
#endif /* LIVEWINDOWSENDABLE_H_ */

View File

@@ -5,8 +5,9 @@
#include "tables/ITableListener.h"
class LiveWindowStatusListener : public ITableListener {
public:
virtual void ValueChanged(ITable* source, const std::string& key, EntryValue value, bool isNew);
public:
virtual void ValueChanged(ITable* source, const std::string& key,
EntryValue value, bool isNew);
};
#endif
#endif

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Copyright (c) FIRST 2008. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -11,35 +12,39 @@
typedef void (*TimerEventHandler)(void *param);
class Notifier : public ErrorBase
{
public:
Notifier(TimerEventHandler handler, void *param = NULL);
virtual ~Notifier();
void StartSingle(double delay);
void StartPeriodic(double period);
void Stop();
private:
static Notifier *timerQueueHead;
static ReentrantSemaphore queueSemaphore;
static void* m_notifier;
static int refcount;
class Notifier : public ErrorBase {
public:
Notifier(TimerEventHandler handler, void *param = NULL);
virtual ~Notifier();
void StartSingle(double delay);
void StartPeriodic(double period);
void Stop();
static void ProcessQueue(uint32_t mask, void *params); // process the timer queue on a timer event
static void UpdateAlarm(); // update the FPGA alarm since the queue has changed
void InsertInQueue(bool reschedule); // insert this Notifier in the timer queue
void DeleteFromQueue(); // delete this Notifier from the timer queue
TimerEventHandler m_handler; // address of the handler
void *m_param; // a parameter to pass to the handler
double m_period; // the relative time (either periodic or single)
double m_expirationTime; // absolute expiration time for the current event
Notifier *m_nextEvent; // next Nofifier event
bool m_periodic; // true if this is a periodic event
bool m_queued; // indicates if this entry is queued
SEMAPHORE_ID m_handlerSemaphore; // held by interrupt manager task while handler call is in progress
private:
static Notifier *timerQueueHead;
static ReentrantSemaphore queueSemaphore;
static void *m_notifier;
static int refcount;
DISALLOW_COPY_AND_ASSIGN(Notifier);
static void ProcessQueue(
uint32_t mask, void *params); // process the timer queue on a timer event
static void
UpdateAlarm(); // update the FPGA alarm since the queue has changed
void InsertInQueue(
bool reschedule); // insert this Notifier in the timer queue
void DeleteFromQueue(); // delete this Notifier from the timer queue
TimerEventHandler m_handler; // address of the handler
void *m_param; // a parameter to pass to the handler
double m_period; // the relative time (either periodic or single)
double m_expirationTime; // absolute expiration time for the current event
Notifier *m_nextEvent; // next Nofifier event
bool m_periodic; // true if this is a periodic event
bool m_queued; // indicates if this entry is queued
SEMAPHORE_ID m_handlerSemaphore; // held by interrupt manager task while
// handler call is in progress
static Task *task;
static void Run();
DISALLOW_COPY_AND_ASSIGN(Notifier);
static Task *task;
static void Run();
};

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Copyright (c) FIRST 2008. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -25,87 +26,85 @@ class Notifier;
class PIDController : public LiveWindowSendable,
public PIDInterface,
public ITableListener {
public:
PIDController(float p, float i, float d, PIDSource *source, PIDOutput *output, float period =
0.05);
PIDController(float p, float i, float d, float f, PIDSource *source, PIDOutput *output,
float period = 0.05);
virtual ~PIDController();
virtual float Get() const;
virtual void SetContinuous(bool continuous = true);
virtual void SetInputRange(float minimumInput, float maximumInput);
virtual void SetOutputRange(float minimumOutput, float maximumOutput);
virtual void SetPID(double p, double i, double d) override;
virtual void SetPID(double p, double i, double d, double f);
virtual double GetP() const override;
virtual double GetI() const override;
virtual double GetD() const override;
virtual double GetF() const;
public:
PIDController(float p, float i, float d, PIDSource *source, PIDOutput *output,
float period = 0.05);
PIDController(float p, float i, float d, float f, PIDSource *source,
PIDOutput *output, float period = 0.05);
virtual ~PIDController();
virtual float Get() const;
virtual void SetContinuous(bool continuous = true);
virtual void SetInputRange(float minimumInput, float maximumInput);
virtual void SetOutputRange(float minimumOutput, float maximumOutput);
virtual void SetPID(double p, double i, double d) override;
virtual void SetPID(double p, double i, double d, double f);
virtual double GetP() const override;
virtual double GetI() const override;
virtual double GetD() const override;
virtual double GetF() const;
virtual void SetSetpoint(float setpoint) override;
virtual double GetSetpoint() const override;
virtual void SetSetpoint(float setpoint) override;
virtual double GetSetpoint() const override;
virtual float GetError() const;
virtual float GetError() const;
virtual void SetTolerance(float percent);
virtual void SetAbsoluteTolerance(float absValue);
virtual void SetPercentTolerance(float percentValue);
virtual bool OnTarget() const;
virtual void SetTolerance(float percent);
virtual void SetAbsoluteTolerance(float absValue);
virtual void SetPercentTolerance(float percentValue);
virtual bool OnTarget() const;
virtual void Enable() override;
virtual void Disable() override;
virtual bool IsEnabled() const override;
virtual void Enable() override;
virtual void Disable() override;
virtual bool IsEnabled() const override;
virtual void Reset() override;
virtual void Reset() override;
virtual void InitTable(ITable* table);
virtual void InitTable(ITable *table);
private:
float m_P; // factor for "proportional" control
float m_I; // factor for "integral" control
float m_D; // factor for "derivative" control
float m_F; // factor for "feed forward" control
float m_maximumOutput; // |maximum output|
float m_minimumOutput; // |minimum output|
float m_maximumInput; // maximum input - limit setpoint to this
float m_minimumInput; // minimum input - limit setpoint to this
bool m_continuous; // do the endpoints wrap around? eg. Absolute encoder
bool m_enabled; //is the pid controller enabled
bool m_destruct; // should the calculate thread stop running
float m_prevError; // the prior sensor input (used to compute velocity)
double m_totalError; //the sum of the errors for use in the integral calc
enum
{
kAbsoluteTolerance,
kPercentTolerance,
kNoTolerance
} m_toleranceType;
float m_tolerance; //the percetage or absolute error that is considered on target
float m_setpoint;
float m_error;
float m_result;
float m_period;
private:
float m_P; // factor for "proportional" control
float m_I; // factor for "integral" control
float m_D; // factor for "derivative" control
float m_F; // factor for "feed forward" control
float m_maximumOutput; // |maximum output|
float m_minimumOutput; // |minimum output|
float m_maximumInput; // maximum input - limit setpoint to this
float m_minimumInput; // minimum input - limit setpoint to this
bool m_continuous; // do the endpoints wrap around? eg. Absolute encoder
bool m_enabled; // is the pid controller enabled
bool m_destruct; // should the calculate thread stop running
float m_prevError; // the prior sensor input (used to compute velocity)
double m_totalError; // the sum of the errors for use in the integral calc
enum { kAbsoluteTolerance, kPercentTolerance, kNoTolerance } m_toleranceType;
float m_tolerance; // the percetage or absolute error that is considered on
// target
float m_setpoint;
float m_error;
float m_result;
float m_period;
MUTEX_ID m_semaphore;
MUTEX_ID m_semaphore;
PIDSource *m_pidInput;
PIDOutput *m_pidOutput;
PIDSource *m_pidInput;
PIDOutput *m_pidOutput;
Notifier* m_controlLoop;
Notifier *m_controlLoop;
void Initialize(float p, float i, float d, float f, PIDSource *source, PIDOutput *output,
float period = 0.05);
static void CallCalculate(void *controller);
void Initialize(float p, float i, float d, float f, PIDSource *source,
PIDOutput *output, float period = 0.05);
static void CallCalculate(void *controller);
virtual ITable* GetTable() const;
virtual std::string GetSmartDashboardType() const;
virtual void ValueChanged(ITable* source, const std::string& key, EntryValue value, bool isNew);
virtual void UpdateTable();
virtual void StartLiveWindowMode();
virtual void StopLiveWindowMode();
protected:
ITable* m_table;
virtual void Calculate();
virtual ITable *GetTable() const;
virtual std::string GetSmartDashboardType() const;
virtual void ValueChanged(ITable *source, const std::string &key,
EntryValue value, bool isNew);
virtual void UpdateTable();
virtual void StartLiveWindowMode();
virtual void StopLiveWindowMode();
DISALLOW_COPY_AND_ASSIGN(PIDController);
protected:
ITable *m_table;
virtual void Calculate();
DISALLOW_COPY_AND_ASSIGN(PIDController);
};

View File

@@ -6,17 +6,17 @@
#include "HAL/Semaphore.hpp"
class PIDInterface : public Controller {
virtual void SetPID(double p, double i, double d)=0;
virtual double GetP() const=0;
virtual double GetI() const=0;
virtual double GetD() const=0;
virtual void SetPID(double p, double i, double d) = 0;
virtual double GetP() const = 0;
virtual double GetI() const = 0;
virtual double GetD() const = 0;
virtual void SetSetpoint(float setpoint)=0;
virtual double GetSetpoint() const=0;
virtual void SetSetpoint(float setpoint) = 0;
virtual double GetSetpoint() const = 0;
virtual void Enable()=0;
virtual void Disable()=0;
virtual bool IsEnabled() const=0;
virtual void Enable() = 0;
virtual void Disable() = 0;
virtual bool IsEnabled() const = 0;
virtual void Reset()=0;
virtual void Reset() = 0;
};

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Copyright (c) FIRST 2008. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -10,11 +11,10 @@
/**
* PIDOutput interface is a generic output for the PID class.
* PWMs use this class.
* Users implement this interface to allow for a PIDController to
* Users implement this interface to allow for a PIDController to
* read directly from the inputs
*/
class PIDOutput
{
public:
virtual void PIDWrite(float output) = 0;
class PIDOutput {
public:
virtual void PIDWrite(float output) = 0;
};

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Copyright (c) FIRST 2008. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -7,12 +8,12 @@
/**
* PIDSource interface is a generic sensor source for the PID class.
* All sensors that can be used with the PID class will implement the PIDSource that
* All sensors that can be used with the PID class will implement the PIDSource
* that
* returns a standard value that will be used in the PID code.
*/
class PIDSource
{
public:
enum PIDSourceParameter {kDistance, kRate, kAngle};
virtual double PIDGet() const = 0;
class PIDSource {
public:
enum PIDSourceParameter { kDistance, kRate, kAngle };
virtual double PIDGet() const = 0;
};

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Copyright (c) FIRST 2008. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -18,23 +19,22 @@
* resources; it just tracks which indices were marked in use by
* Allocate and not yet freed by Free.
*/
class Resource : public ErrorBase
{
public:
virtual ~Resource();
static void CreateResourceObject(Resource **r, uint32_t elements);
uint32_t Allocate(const char *resourceDesc);
uint32_t Allocate(uint32_t index, const char *resourceDesc);
void Free(uint32_t index);
class Resource : public ErrorBase {
public:
virtual ~Resource();
static void CreateResourceObject(Resource **r, uint32_t elements);
uint32_t Allocate(const char *resourceDesc);
uint32_t Allocate(uint32_t index, const char *resourceDesc);
void Free(uint32_t index);
private:
explicit Resource(uint32_t size);
private:
explicit Resource(uint32_t size);
bool *m_isAllocated;
ReentrantSemaphore m_allocateLock;
uint32_t m_size;
bool *m_isAllocated;
ReentrantSemaphore m_allocateLock;
uint32_t m_size;
static ReentrantSemaphore m_createLock;
static ReentrantSemaphore m_createLock;
DISALLOW_COPY_AND_ASSIGN(Resource);
DISALLOW_COPY_AND_ASSIGN(Resource);
};

View File

@@ -5,29 +5,25 @@
/*----------------------------------------------------------------------------*/
#pragma once
class RobotStateInterface
{
public:
virtual ~RobotStateInterface() {};
virtual bool IsDisabled() const = 0;
virtual bool IsEnabled() const = 0;
virtual bool IsOperatorControl() const = 0;
virtual bool IsAutonomous() const = 0;
virtual bool IsTest() const = 0;
class RobotStateInterface {
public:
virtual ~RobotStateInterface(){};
virtual bool IsDisabled() const = 0;
virtual bool IsEnabled() const = 0;
virtual bool IsOperatorControl() const = 0;
virtual bool IsAutonomous() const = 0;
virtual bool IsTest() const = 0;
};
class RobotState
{
private:
static RobotStateInterface* impl;
public:
static void SetImplementation(RobotStateInterface* i);
static bool IsDisabled();
static bool IsEnabled();
static bool IsOperatorControl();
static bool IsAutonomous();
static bool IsTest();
class RobotState {
private:
static RobotStateInterface* impl;
public:
static void SetImplementation(RobotStateInterface* i);
static bool IsDisabled();
static bool IsEnabled();
static bool IsOperatorControl();
static bool IsAutonomous();
static bool IsTest();
};

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Copyright (c) FIRST 2008. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -11,49 +12,46 @@
/**
* Base class for all sensors.
* Stores most recent status information as well as containing utility functions for checking
* Stores most recent status information as well as containing utility functions
* for checking
* channels and error processing.
*/
class SensorBase : public ErrorBase
{
public:
SensorBase();
virtual ~SensorBase();
static void DeleteSingletons();
class SensorBase : public ErrorBase {
public:
SensorBase();
virtual ~SensorBase();
static void DeleteSingletons();
static uint32_t GetDefaultSolenoidModule()
{
return 0;
}
static uint32_t GetDefaultSolenoidModule() { return 0; }
static bool CheckSolenoidModule(uint8_t moduleNumber);
static bool CheckDigitalChannel(uint32_t channel);
static bool CheckRelayChannel(uint32_t channel);
static bool CheckPWMChannel(uint32_t channel);
static bool CheckAnalogInput(uint32_t channel);
static bool CheckAnalogOutput(uint32_t channel);
static bool CheckSolenoidChannel(uint32_t channel);
static bool CheckPDPChannel(uint32_t channel);
static bool CheckSolenoidModule(uint8_t moduleNumber);
static bool CheckDigitalChannel(uint32_t channel);
static bool CheckRelayChannel(uint32_t channel);
static bool CheckPWMChannel(uint32_t channel);
static bool CheckAnalogInput(uint32_t channel);
static bool CheckAnalogOutput(uint32_t channel);
static bool CheckSolenoidChannel(uint32_t channel);
static bool CheckPDPChannel(uint32_t channel);
static const uint32_t kDigitalChannels = 26;
static const uint32_t kAnalogInputs = 8;
static const uint32_t kAnalogOutputs = 2;
static const uint32_t kSolenoidChannels = 8;
static const uint32_t kSolenoidModules = 2;
static const uint32_t kPwmChannels = 20;
static const uint32_t kRelayChannels = 8;
static const uint32_t kPDPChannels = 16;
static const uint32_t kChassisSlots = 8;
static const uint32_t kDigitalChannels = 26;
static const uint32_t kAnalogInputs = 8;
static const uint32_t kAnalogOutputs = 2;
static const uint32_t kSolenoidChannels = 8;
static const uint32_t kSolenoidModules = 2;
static const uint32_t kPwmChannels = 20;
static const uint32_t kRelayChannels = 8;
static const uint32_t kPDPChannels = 16;
static const uint32_t kChassisSlots = 8;
protected:
void AddToSingletonList();
protected:
void AddToSingletonList();
static void* m_digital_ports[kDigitalChannels];
static void* m_relay_ports[kRelayChannels];
static void* m_pwm_ports[kPwmChannels];
static void* m_digital_ports[kDigitalChannels];
static void* m_relay_ports[kRelayChannels];
static void* m_pwm_ports[kPwmChannels];
private:
DISALLOW_COPY_AND_ASSIGN(SensorBase);
static SensorBase *m_singletonList;
SensorBase *m_nextSingleton;
private:
DISALLOW_COPY_AND_ASSIGN(SensorBase);
static SensorBase* m_singletonList;
SensorBase* m_nextSingleton;
};

View File

@@ -8,22 +8,21 @@
#ifndef NAMEDSENDABLE_H_
#define NAMEDSENDABLE_H_
#include <string>
#include "SmartDashboard/Sendable.h"
/**
* The interface for sendable objects that gives the sendable a default name in the Smart Dashboard
*
* The interface for sendable objects that gives the sendable a default name in
* the Smart Dashboard
*
*/
class NamedSendable : public Sendable
{
public:
/**
* @return the name of the subtable of SmartDashboard that the Sendable object will use
*/
virtual std::string GetName() = 0;
class NamedSendable : public Sendable {
public:
/**
* @return the name of the subtable of SmartDashboard that the Sendable object
* will use
*/
virtual std::string GetName() = 0;
};
#endif /* NAMEDSENDABLE_H_ */

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -10,24 +11,24 @@
#include <string>
#include "tables/ITable.h"
class Sendable
{
public:
/**
* Initializes a table for this sendable object.
* @param subtable The table to put the values in.
*/
virtual void InitTable(ITable* subtable) = 0;
class Sendable {
public:
/**
* Initializes a table for this sendable object.
* @param subtable The table to put the values in.
*/
virtual void InitTable(ITable* subtable) = 0;
/**
* @return the table that is currently associated with the sendable
*/
virtual ITable* GetTable() const = 0;
/**
* @return the table that is currently associated with the sendable
*/
virtual ITable* GetTable() const = 0;
/**
* @return the string representation of the named data type that will be used by the smart dashboard for this sendable
*/
virtual std::string GetSmartDashboardType() const = 0;
/**
* @return the string representation of the named data type that will be used
* by the smart dashboard for this sendable
*/
virtual std::string GetSmartDashboardType() const = 0;
};
#endif

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -13,35 +14,39 @@
#include <string>
/**
* The {@link SendableChooser} class is a useful tool for presenting a selection of options
* The {@link SendableChooser} class is a useful tool for presenting a selection
* of options
* to the {@link SmartDashboard}.
*
* <p>For instance, you may wish to be able to select between multiple autonomous modes.
* You can do this by putting every possible {@link Command} you want to run as an autonomous into
* a {@link SendableChooser} and then put it into the {@link SmartDashboard} to have a list of options
* appear on the laptop. Once autonomous starts, simply ask the {@link SendableChooser} what the selected
* <p>For instance, you may wish to be able to select between multiple
* autonomous modes.
* You can do this by putting every possible {@link Command} you want to run as
* an autonomous into
* a {@link SendableChooser} and then put it into the {@link SmartDashboard} to
* have a list of options
* appear on the laptop. Once autonomous starts, simply ask the {@link
* SendableChooser} what the selected
* value is.</p>
*
* @see SmartDashboard
*/
class SendableChooser : public Sendable
{
public:
SendableChooser();
virtual ~SendableChooser() {};
class SendableChooser : public Sendable {
public:
SendableChooser();
virtual ~SendableChooser(){};
void AddObject(const char *name, void *object);
void AddDefault(const char *name, void *object);
void *GetSelected();
void AddObject(const char *name, void *object);
void AddDefault(const char *name, void *object);
void *GetSelected();
virtual void InitTable(ITable* subtable);
virtual ITable* GetTable() const;
virtual std::string GetSmartDashboardType() const;
virtual void InitTable(ITable *subtable);
virtual ITable *GetTable() const;
virtual std::string GetSmartDashboardType() const;
private:
std::string m_defaultChoice;
std::map<std::string, void *> m_choices;
ITable *m_table;
private:
std::string m_defaultChoice;
std::map<std::string, void *> m_choices;
ITable *m_table;
};
#endif

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -14,44 +15,44 @@
#include "SmartDashboard/NamedSendable.h"
#include "tables/ITable.h"
class SmartDashboard : public SensorBase {
public:
static void init();
class SmartDashboard : public SensorBase
{
public:
static void init();
static void PutData(std::string key, Sendable *data);
static void PutData(NamedSendable *value);
static Sendable *GetData(std::string keyName);
static void PutData(std::string key, Sendable *data);
static void PutData(NamedSendable *value);
static Sendable* GetData(std::string keyName);
static void PutBoolean(std::string keyName, bool value);
static bool GetBoolean(std::string keyName);
static bool GetBoolean(std::string keyName, bool defaultValue);
static void PutBoolean(std::string keyName, bool value);
static bool GetBoolean(std::string keyName);
static bool GetBoolean(std::string keyName, bool defaultValue);
static void PutNumber(std::string keyName, double value);
static double GetNumber(std::string keyName);
static double GetNumber(std::string keyName, double defaultValue);
static void PutNumber(std::string keyName, double value);
static double GetNumber(std::string keyName);
static double GetNumber(std::string keyName, double defaultValue);
static void PutString(std::string keyName, std::string value);
static int GetString(std::string keyName, char *value, unsigned int valueLen);
static std::string GetString(std::string keyName);
static std::string GetString(std::string keyName, std::string defaultValue);
static void PutString(std::string keyName, std::string value);
static int GetString(std::string keyName, char *value, unsigned int valueLen);
static std::string GetString(std::string keyName);
static std::string GetString(std::string keyName, std::string defaultValue);
static void PutValue(std::string keyName, ComplexData &value);
static void RetrieveValue(std::string keyName, ComplexData &value);
static void PutValue(std::string keyName, ComplexData& value);
static void RetrieveValue(std::string keyName, ComplexData& value);
private:
SmartDashboard();
virtual ~SmartDashboard();
DISALLOW_COPY_AND_ASSIGN(SmartDashboard);
private:
SmartDashboard();
virtual ~SmartDashboard();
DISALLOW_COPY_AND_ASSIGN(SmartDashboard);
/** The {@link NetworkTable} used by {@link SmartDashboard} */
static ITable* m_table;
/** The {@link NetworkTable} used by {@link SmartDashboard} */
static ITable *m_table;
/**
* A map linking tables in the SmartDashboard to the {@link SmartDashboardData} objects
* they came from.
*/
static std::map<ITable *, Sendable *> m_tablesToData;
/**
* A map linking tables in the SmartDashboard to the {@link
* SmartDashboardData} objects
* they came from.
*/
static std::map<ITable *, Sendable *> m_tablesToData;
};
#endif

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Copyright (c) FIRST 2008. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -12,41 +13,40 @@
* WPI task is a wrapper for the native Task object.
* All WPILib tasks are managed by a static task manager for simplified cleanup.
**/
class Task : public ErrorBase
{
public:
static const uint32_t kDefaultPriority = 101;
class Task : public ErrorBase {
public:
static const uint32_t kDefaultPriority = 101;
Task(const char* name, FUNCPTR function, int32_t priority = kDefaultPriority,
uint32_t stackSize = 20000);
virtual ~Task();
Task(const char* name, FUNCPTR function, int32_t priority = kDefaultPriority,
uint32_t stackSize = 20000);
virtual ~Task();
bool Start(uint32_t arg0 = 0, uint32_t arg1 = 0, uint32_t arg2 = 0, uint32_t arg3 = 0,
uint32_t arg4 = 0, uint32_t arg5 = 0, uint32_t arg6 = 0, uint32_t arg7 = 0,
uint32_t arg8 = 0, uint32_t arg9 = 0);
bool Restart();
bool Stop();
bool Start(uint32_t arg0 = 0, uint32_t arg1 = 0, uint32_t arg2 = 0,
uint32_t arg3 = 0, uint32_t arg4 = 0, uint32_t arg5 = 0,
uint32_t arg6 = 0, uint32_t arg7 = 0, uint32_t arg8 = 0,
uint32_t arg9 = 0);
bool Restart();
bool Stop();
bool IsReady() const;
bool IsSuspended() const;
bool IsReady() const;
bool IsSuspended() const;
bool Suspend();
bool Resume();
bool Suspend();
bool Resume();
bool Verify() const;
bool Verify() const;
int32_t GetPriority();
bool SetPriority(int32_t priority);
const char* GetName() const;
TASK GetID() const;
int32_t GetPriority();
bool SetPriority(int32_t priority);
const char* GetName() const;
TASK GetID() const;
private:
FUNCPTR m_function;
char* m_taskName;
TASK m_taskID;
uint32_t m_stackSize;
int m_priority;
bool HandleError(STATUS results);
DISALLOW_COPY_AND_ASSIGN(Task);
private:
FUNCPTR m_function;
char* m_taskName;
TASK m_taskID;
uint32_t m_stackSize;
int m_priority;
bool HandleError(STATUS results);
DISALLOW_COPY_AND_ASSIGN(Task);
};

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Copyright (c) FIRST 2008. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -16,33 +17,35 @@ double GetTime();
/**
* Timer objects measure accumulated time in seconds.
* The timer object functions like a stopwatch. It can be started, stopped, and cleared. When the
* timer is running its value counts up in seconds. When stopped, the timer holds the current
* value. The implementation simply records the time when started and subtracts the current time
* The timer object functions like a stopwatch. It can be started, stopped, and
* cleared. When the
* timer is running its value counts up in seconds. When stopped, the timer
* holds the current
* value. The implementation simply records the time when started and subtracts
* the current time
* whenever the value is requested.
*/
class Timer
{
public:
Timer();
virtual ~Timer();
double Get() const;
void Reset();
void Start();
void Stop();
bool HasPeriodPassed(double period);
class Timer {
public:
Timer();
virtual ~Timer();
double Get() const;
void Reset();
void Start();
void Stop();
bool HasPeriodPassed(double period);
static double GetFPGATimestamp();
static double GetPPCTimestamp();
static double GetMatchTime();
// The time, in seconds, at which the 32-bit FPGA timestamp rolls over to 0
static constexpr double kRolloverTime = (1ll << 32) / 1e6;
static double GetFPGATimestamp();
static double GetPPCTimestamp();
static double GetMatchTime();
private:
double m_startTime;
double m_accumulatedTime;
bool m_running;
MUTEX_ID m_semaphore;
DISALLOW_COPY_AND_ASSIGN(Timer);
// The time, in seconds, at which the 32-bit FPGA timestamp rolls over to 0
static constexpr double kRolloverTime = (1ll << 32) / 1e6;
private:
double m_startTime;
double m_accumulatedTime;
bool m_running;
MUTEX_ID m_semaphore;
DISALLOW_COPY_AND_ASSIGN(Timer);
};

View File

@@ -1,5 +1,6 @@
/*---------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Copyright (c) FIRST 2008. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*---------------------------------------------------------------------------*/
@@ -12,18 +13,34 @@
#include <stdint.h>
#include <string>
#define wpi_assert(condition) wpi_assert_impl(condition, #condition, NULL, __FILE__, __LINE__, __FUNCTION__)
#define wpi_assertWithMessage(condition, message) wpi_assert_impl(condition, #condition, message, __FILE__, __LINE__, __FUNCTION__)
#define wpi_assert(condition) \
wpi_assert_impl(condition, #condition, NULL, __FILE__, __LINE__, __FUNCTION__)
#define wpi_assertWithMessage(condition, message) \
wpi_assert_impl(condition, #condition, message, __FILE__, __LINE__, \
__FUNCTION__)
#define wpi_assertEqual(a, b) wpi_assertEqual_impl(a, b, #a, #b, NULL, __FILE__, __LINE__, __FUNCTION__)
#define wpi_assertEqualWithMessage(a, b, message) wpi_assertEqual_impl(a, b, #a, #b, message, __FILE__, __LINE__, __FUNCTION__)
#define wpi_assertEqual(a, b) \
wpi_assertEqual_impl(a, b, #a, #b, NULL, __FILE__, __LINE__, __FUNCTION__)
#define wpi_assertEqualWithMessage(a, b, message) \
wpi_assertEqual_impl(a, b, #a, #b, message, __FILE__, __LINE__, __FUNCTION__)
#define wpi_assertNotEqual(a, b) wpi_assertNotEqual_impl(a, b, #a, #b, NULL, __FILE__, __LINE__, __FUNCTION__)
#define wpi_assertNotEqualWithMessage(a, b, message) wpi_assertNotEqual_impl(a, b, #a, #b, message, __FILE__, __LINE__, __FUNCTION__)
#define wpi_assertNotEqual(a, b) \
wpi_assertNotEqual_impl(a, b, #a, #b, NULL, __FILE__, __LINE__, __FUNCTION__)
#define wpi_assertNotEqualWithMessage(a, b, message) \
wpi_assertNotEqual_impl(a, b, #a, #b, message, __FILE__, __LINE__, \
__FUNCTION__)
bool wpi_assert_impl(bool conditionValue, const char *conditionText, const char *message, const char *fileName, uint32_t lineNumber, const char *funcName);
bool wpi_assertEqual_impl(int valueA, int valueB, const char *valueAString, const char *valueBString, const char *message, const char *fileName,uint32_t lineNumber, const char *funcName);
bool wpi_assertNotEqual_impl(int valueA, int valueB, const char *valueAString, const char *valueBString, const char *message, const char *fileName,uint32_t lineNumber, const char *funcName);
bool wpi_assert_impl(bool conditionValue, const char *conditionText,
const char *message, const char *fileName,
uint32_t lineNumber, const char *funcName);
bool wpi_assertEqual_impl(int valueA, int valueB, const char *valueAString,
const char *valueBString, const char *message,
const char *fileName, uint32_t lineNumber,
const char *funcName);
bool wpi_assertNotEqual_impl(int valueA, int valueB, const char *valueAString,
const char *valueBString, const char *message,
const char *fileName, uint32_t lineNumber,
const char *funcName);
void wpi_suspendOnAssertEnabled(bool enabled);

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Copyright (c) FIRST 2008. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -8,17 +9,20 @@
#include "stdint.h"
#ifdef WPI_ERRORS_DEFINE_STRINGS
#define S(label, offset, message) const char *wpi_error_s_##label = message ; \
const int32_t wpi_error_value_##label = offset
#define S(label, offset, message) \
const char *wpi_error_s_##label = message; \
const int32_t wpi_error_value_##label = offset
#else
#define S(label, offset, message) extern const char *wpi_error_s_##label ; \
const int32_t wpi_error_value_##label = offset
#define S(label, offset, message) \
extern const char *wpi_error_s_##label; \
const int32_t wpi_error_value_##label = offset
#endif
/*
* Fatal errors
*/
S(ModuleIndexOutOfRange, -1, "Allocating module that is out of range or not found");
S(ModuleIndexOutOfRange, -1,
"Allocating module that is out of range or not found");
S(ChannelIndexOutOfRange, -1, "Allocating channel that is out of range");
S(NotAllocated, -2, "Attempting to free unallocated resource");
S(ResourceAlreadyAllocated, -3, "Attempted to reuse an allocated resource");
@@ -26,10 +30,13 @@ S(NoAvailableResources, -4, "No available resources to allocate");
S(NullParameter, -5, "A pointer parameter to a method is NULL");
S(Timeout, -6, "A timeout has been exceeded");
S(CompassManufacturerError, -7, "Compass manufacturer doesn't match HiTechnic");
S(CompassTypeError, -8, "Compass type doesn't match expected type for HiTechnic compass");
S(CompassTypeError, -8,
"Compass type doesn't match expected type for HiTechnic compass");
S(IncompatibleMode, -9, "The object is in an incompatible mode");
S(AnalogTriggerLimitOrderError, -10, "AnalogTrigger limits error. Lower limit > Upper Limit");
S(AnalogTriggerPulseOutputError, -11, "Attempted to read AnalogTrigger pulse output.");
S(AnalogTriggerLimitOrderError, -10,
"AnalogTrigger limits error. Lower limit > Upper Limit");
S(AnalogTriggerPulseOutputError, -11,
"Attempted to read AnalogTrigger pulse output.");
S(TaskError, -12, "Task can't be started");
S(TaskIDError, -13, "Task error: Invalid ID.");
S(TaskDeletedError, -14, "Task error: Task already deleted.");
@@ -37,22 +44,33 @@ S(TaskOptionsError, -15, "Task error: Invalid options.");
S(TaskMemoryError, -16, "Task can't be started due to insufficient memory.");
S(TaskPriorityError, -17, "Task error: Invalid priority [1-255].");
S(DriveUninitialized, -18, "RobotDrive not initialized for the C interface");
S(CompressorNonMatching, -19, "Compressor slot/channel doesn't match previous instance");
S(CompressorNonMatching, -19,
"Compressor slot/channel doesn't match previous instance");
S(CompressorAlreadyDefined, -20, "Creating a second compressor instance");
S(CompressorUndefined, -21, "Using compressor functions without defining compressor");
S(InconsistentArrayValueAdded, -22, "When packing data into an array to the dashboard, not all values added were of the same type.");
S(MismatchedComplexTypeClose, -23, "When packing data to the dashboard, a Close for a complex type was called without a matching Open.");
S(DashboardDataOverflow, -24, "When packing data to the dashboard, too much data was packed and the buffer overflowed.");
S(DashboardDataCollision, -25, "The same buffer was used for packing data and for printing.");
S(CompressorUndefined, -21,
"Using compressor functions without defining compressor");
S(InconsistentArrayValueAdded, -22,
"When packing data into an array to the dashboard, not all values added were "
"of the same type.");
S(MismatchedComplexTypeClose, -23,
"When packing data to the dashboard, a Close for a complex type was called "
"without a matching Open.");
S(DashboardDataOverflow, -24,
"When packing data to the dashboard, too much data was packed and the buffer "
"overflowed.");
S(DashboardDataCollision, -25,
"The same buffer was used for packing data and for printing.");
S(EnhancedIOMissing, -26, "IO is not attached or Enhanced IO is not enabled.");
S(LineNotOutput, -27, "Cannot SetDigitalOutput for a line not configured for output.");
S(LineNotOutput, -27,
"Cannot SetDigitalOutput for a line not configured for output.");
S(ParameterOutOfRange, -28, "A parameter is out of range.");
S(SPIClockRateTooLow, -29, "SPI clock rate was below the minimum supported");
S(JaguarVersionError, -30, "Jaguar firmware version error");
S(JaguarMessageNotFound, -31, "Jaguar message not found");
S(NetworkTablesReadError, -40, "Error reading NetworkTables socket");
S(NetworkTablesBufferFull, -41, "Buffer full writing to NetworkTables socket");
S(NetworkTablesWrongType, -42, "The wrong type was read from the NetworkTables entry");
S(NetworkTablesWrongType, -42,
"The wrong type was read from the NetworkTables entry");
S(NetworkTablesCorrupt, -43, "NetworkTables data stream is corrupt");
S(SmartDashboardMissingKey, -43, "SmartDashboard data does not exist");
S(CommandIllegalUse, -50, "Illegal use of Command");
@@ -62,19 +80,23 @@ S(UnsupportedInSimulation, -80, "Unsupported in simulation");
* Warnings
*/
S(SampleRateTooHigh, 1, "Analog module sample rate is too high");
S(VoltageOutOfRange, 2, "Voltage to convert to raw value is out of range [-10; 10]");
S(VoltageOutOfRange, 2,
"Voltage to convert to raw value is out of range [-10; 10]");
S(CompressorTaskError, 3, "Compressor task won't start");
S(LoopTimingError, 4, "Digital module loop timing is not the expected value");
S(NonBinaryDigitalValue, 5, "Digital output value is not 0 or 1");
S(IncorrectBatteryChannel, 6, "Battery measurement channel is not correct value");
S(IncorrectBatteryChannel, 6,
"Battery measurement channel is not correct value");
S(BadJoystickIndex, 7, "Joystick index is out of range, should be 0-3");
S(BadJoystickAxis, 8, "Joystick axis or POV is out of range");
S(InvalidMotorIndex, 9, "Motor index is out of range, should be 0-3");
S(DriverStationTaskError, 10, "Driver Station task won't start");
S(EnhancedIOPWMPeriodOutOfRange, 11, "Driver Station Enhanced IO PWM Output period out of range.");
S(EnhancedIOPWMPeriodOutOfRange, 11,
"Driver Station Enhanced IO PWM Output period out of range.");
S(SPIWriteNoMOSI, 12, "Cannot write to SPI port with no MOSI output");
S(SPIReadNoMISO, 13, "Cannot read from SPI port with no MISO input");
S(SPIReadNoData, 14, "No data available to read from SPI");
S(IncompatibleState, 15, "Incompatible State: The operation cannot be completed");
S(IncompatibleState, 15,
"Incompatible State: The operation cannot be completed");
#undef S

View File

@@ -8,45 +8,38 @@
/**
* Interface for 3-axis accelerometers
*/
class Accelerometer
{
public:
virtual ~Accelerometer() {};
class Accelerometer {
public:
virtual ~Accelerometer(){};
enum Range
{
kRange_2G = 0,
kRange_4G = 1,
kRange_8G = 2,
kRange_16G = 3
};
enum Range { kRange_2G = 0, kRange_4G = 1, kRange_8G = 2, kRange_16G = 3 };
/**
* Common interface for setting the measuring range of an accelerometer.
*
* @param range The maximum acceleration, positive or negative, that the
* accelerometer will measure. Not all accelerometers support all ranges.
*/
virtual void SetRange(Range range) = 0;
/**
* Common interface for setting the measuring range of an accelerometer.
*
* @param range The maximum acceleration, positive or negative, that the
* accelerometer will measure. Not all accelerometers support all ranges.
*/
virtual void SetRange(Range range) = 0;
/**
* Common interface for getting the x axis acceleration
*
* @return The acceleration along the x axis in g-forces
*/
virtual double GetX() = 0;
/**
* Common interface for getting the x axis acceleration
*
* @return The acceleration along the x axis in g-forces
*/
virtual double GetX() = 0;
/**
* Common interface for getting the y axis acceleration
*
* @return The acceleration along the y axis in g-forces
*/
virtual double GetY() = 0;
/**
* Common interface for getting the y axis acceleration
*
* @return The acceleration along the y axis in g-forces
*/
virtual double GetY() = 0;
/**
* Common interface for getting the z axis acceleration
*
* @return The acceleration along the z axis in g-forces
*/
virtual double GetZ() = 0;
/**
* Common interface for getting the z axis acceleration
*
* @return The acceleration along the z axis in g-forces
*/
virtual double GetZ() = 0;
};

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Copyright (c) FIRST 2008. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -12,16 +13,15 @@
/**
* Interface for potentiometers.
*/
class Potentiometer : public PIDSource
{
public:
virtual ~Potentiometer() {};
/**
* Common interface for getting the current value of a potentiometer.
*
* @return The current set speed. Value is between -1.0 and 1.0.
*/
virtual double Get() const = 0;
class Potentiometer : public PIDSource {
public:
virtual ~Potentiometer(){};
/**
* Common interface for getting the current value of a potentiometer.
*
* @return The current set speed. Value is between -1.0 and 1.0.
*/
virtual double Get() const = 0;
};
#endif

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -10,9 +11,7 @@
* Specifies the command to run when a button is first pressed
* @param command The pointer to the command to run
*/
void Button::WhenPressed(Command *command) {
WhenActive(command);
}
void Button::WhenPressed(Command *command) { WhenActive(command); }
/**
* Specifies the command to be scheduled while the button is pressed
@@ -20,31 +19,23 @@ void Button::WhenPressed(Command *command) {
* be canceled when the button is released.
* @param command The pointer to the command to run
*/
void Button::WhileHeld(Command *command) {
WhileActive(command);
}
void Button::WhileHeld(Command *command) { WhileActive(command); }
/**
* Specifies the command to run when the button is released
* The command will be scheduled a single time.
* @param The pointer to the command to run
*/
void Button::WhenReleased(Command *command) {
WhenInactive(command);
}
void Button::WhenReleased(Command *command) { WhenInactive(command); }
/**
* Cancels the specificed command when the button is pressed
* @param The command to be canceled
*/
void Button::CancelWhenPressed(Command *command) {
CancelWhenActive(command);
}
void Button::CancelWhenPressed(Command *command) { CancelWhenActive(command); }
/**
* Toggle the specified command when the button is pressed
* @param The command to be toggled
*/
void Button::ToggleWhenPressed(Command *command) {
ToggleWhenActive(command);
}
void Button::ToggleWhenPressed(Command *command) { ToggleWhenActive(command); }

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -8,14 +9,7 @@
#include "Commands/Scheduler.h"
ButtonScheduler::ButtonScheduler(bool last, Trigger *button, Command *orders) :
m_pressedLast(last),
m_button(button),
m_command(orders)
{
}
ButtonScheduler::ButtonScheduler(bool last, Trigger *button, Command *orders)
: m_pressedLast(last), m_button(button), m_command(orders) {}
void ButtonScheduler::Start()
{
Scheduler::GetInstance()->AddButton(this);
}
void ButtonScheduler::Start() { Scheduler::GetInstance()->AddButton(this); }

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -9,21 +10,19 @@
#include "Buttons/Button.h"
#include "Commands/Command.h"
CancelButtonScheduler::CancelButtonScheduler(bool last, Trigger *button, Command *orders) :
ButtonScheduler(last, button, orders)
{
pressedLast = m_button->Grab();
CancelButtonScheduler::CancelButtonScheduler(bool last, Trigger *button,
Command *orders)
: ButtonScheduler(last, button, orders) {
pressedLast = m_button->Grab();
}
void CancelButtonScheduler::Execute()
{
if (m_button->Grab()) {
if (!pressedLast) {
pressedLast = true;
m_command->Cancel();
}
} else {
pressedLast = false;
void CancelButtonScheduler::Execute() {
if (m_button->Grab()) {
if (!pressedLast) {
pressedLast = true;
m_command->Cancel();
}
} else {
pressedLast = false;
}
}

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -9,24 +10,18 @@
#include "Buttons/Button.h"
#include "Commands/Command.h"
HeldButtonScheduler::HeldButtonScheduler(bool last, Trigger *button, Command *orders) :
ButtonScheduler(last, button, orders)
{
}
HeldButtonScheduler::HeldButtonScheduler(bool last, Trigger *button,
Command *orders)
: ButtonScheduler(last, button, orders) {}
void HeldButtonScheduler::Execute()
{
if (m_button->Grab())
{
m_pressedLast = true;
m_command->Start();
}
else
{
if (m_pressedLast)
{
m_pressedLast = false;
m_command->Cancel();
}
}
void HeldButtonScheduler::Execute() {
if (m_button->Grab()) {
m_pressedLast = true;
m_command->Start();
} else {
if (m_pressedLast) {
m_pressedLast = false;
m_command->Cancel();
}
}
}

View File

@@ -1,34 +1,19 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
#include "Buttons/InternalButton.h"
InternalButton::InternalButton() :
m_pressed(false),
m_inverted(false)
{
}
InternalButton::InternalButton() : m_pressed(false), m_inverted(false) {}
InternalButton::InternalButton(bool inverted) :
m_pressed(inverted),
m_inverted(inverted)
{
}
InternalButton::InternalButton(bool inverted)
: m_pressed(inverted), m_inverted(inverted) {}
void InternalButton::SetInverted(bool inverted)
{
m_inverted = inverted;
}
void InternalButton::SetInverted(bool inverted) { m_inverted = inverted; }
void InternalButton::SetPressed(bool pressed)
{
m_pressed = pressed;
}
void InternalButton::SetPressed(bool pressed) { m_pressed = pressed; }
bool InternalButton::Get()
{
return m_pressed ^ m_inverted;
}
bool InternalButton::Get() { return m_pressed ^ m_inverted; }

View File

@@ -1,18 +1,13 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
#include "Buttons/JoystickButton.h"
JoystickButton::JoystickButton(GenericHID *joystick, int buttonNumber) :
m_joystick(joystick),
m_buttonNumber(buttonNumber)
{
}
JoystickButton::JoystickButton(GenericHID *joystick, int buttonNumber)
: m_joystick(joystick), m_buttonNumber(buttonNumber) {}
bool JoystickButton::Get()
{
return m_joystick->GetRawButton(m_buttonNumber);
}
bool JoystickButton::Get() { return m_joystick->GetRawButton(m_buttonNumber); }

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -7,23 +8,18 @@
#include "Buttons/NetworkButton.h"
#include "networktables/NetworkTable.h"
NetworkButton::NetworkButton(const char *tableName, const char *field) ://TODO how is this supposed to work???
m_netTable(NetworkTable::GetTable(tableName)),
m_field(field)
{
}
NetworkButton::NetworkButton(const char *tableName, const char *field)
: // TODO how is this supposed to work???
m_netTable(NetworkTable::GetTable(tableName)),
m_field(field) {}
NetworkButton::NetworkButton(ITable *table, const char *field) :
m_netTable(table),
m_field(field)
{
}
NetworkButton::NetworkButton(ITable *table, const char *field)
: m_netTable(table), m_field(field) {}
bool NetworkButton::Get()
{
/*if (m_netTable->isConnected())
return m_netTable->GetBoolean(m_field.c_str());
else
return false;*/
return m_netTable->GetBoolean(m_field);
bool NetworkButton::Get() {
/*if (m_netTable->isConnected())
return m_netTable->GetBoolean(m_field.c_str());
else
return false;*/
return m_netTable->GetBoolean(m_field);
}

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -9,23 +10,17 @@
#include "Buttons/Button.h"
#include "Commands/Command.h"
PressedButtonScheduler::PressedButtonScheduler(bool last, Trigger *button, Command *orders) :
ButtonScheduler(last, button, orders)
{
}
PressedButtonScheduler::PressedButtonScheduler(bool last, Trigger *button,
Command *orders)
: ButtonScheduler(last, button, orders) {}
void PressedButtonScheduler::Execute()
{
if (m_button->Grab())
{
if (!m_pressedLast)
{
m_pressedLast = true;
m_command->Start();
}
}
else
{
m_pressedLast = false;
}
void PressedButtonScheduler::Execute() {
if (m_button->Grab()) {
if (!m_pressedLast) {
m_pressedLast = true;
m_command->Start();
}
} else {
m_pressedLast = false;
}
}

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -9,23 +10,17 @@
#include "Buttons/Button.h"
#include "Commands/Command.h"
ReleasedButtonScheduler::ReleasedButtonScheduler(bool last, Trigger *button, Command *orders) :
ButtonScheduler(last, button, orders)
{
}
ReleasedButtonScheduler::ReleasedButtonScheduler(bool last, Trigger *button,
Command *orders)
: ButtonScheduler(last, button, orders) {}
void ReleasedButtonScheduler::Execute()
{
if (m_button->Grab())
{
m_pressedLast = true;
}
else
{
if (m_pressedLast)
{
m_pressedLast = false;
m_command->Start();
}
}
void ReleasedButtonScheduler::Execute() {
if (m_button->Grab()) {
m_pressedLast = true;
} else {
if (m_pressedLast) {
m_pressedLast = false;
m_command->Start();
}
}
}

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -10,23 +11,22 @@
#include "Commands/Command.h"
ToggleButtonScheduler::ToggleButtonScheduler(bool last, Trigger *button,
Command *orders) :
ButtonScheduler(last, button, orders) {
pressedLast = m_button->Grab();
Command *orders)
: ButtonScheduler(last, button, orders) {
pressedLast = m_button->Grab();
}
void ToggleButtonScheduler::Execute() {
if (m_button->Grab()) {
if (!pressedLast) {
pressedLast = true;
if (m_command->IsRunning()) {
m_command->Cancel();
} else {
m_command->Start();
}
}
} else {
pressedLast = false;
}
if (m_button->Grab()) {
if (!pressedLast) {
pressedLast = true;
if (m_command->IsRunning()) {
m_command->Cancel();
} else {
m_command->Start();
}
}
} else {
pressedLast = false;
}
}

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -12,64 +13,54 @@
#include "Buttons/ToggleButtonScheduler.h"
#include "Buttons/CancelButtonScheduler.h"
Trigger::Trigger() {
m_table = NULL;
Trigger::Trigger() { m_table = NULL; }
bool Trigger::Grab() {
if (Get())
return true;
else if (m_table != NULL) {
// if (m_table->isConnected())//TODO is connected on button?
return m_table->GetBoolean("pressed");
/*else
return false;*/
} else
return false;
}
bool Trigger::Grab()
{
if (Get())
return true;
else if (m_table != NULL)
{
//if (m_table->isConnected())//TODO is connected on button?
return m_table->GetBoolean("pressed");
/*else
return false;*/
}
else
return false;
void Trigger::WhenActive(Command *command) {
PressedButtonScheduler *pbs =
new PressedButtonScheduler(Grab(), this, command);
pbs->Start();
}
void Trigger::WhenActive(Command *command)
{
PressedButtonScheduler *pbs = new PressedButtonScheduler(Grab(), this, command);
pbs->Start();
void Trigger::WhileActive(Command *command) {
HeldButtonScheduler *hbs = new HeldButtonScheduler(Grab(), this, command);
hbs->Start();
}
void Trigger::WhileActive(Command *command)
{
HeldButtonScheduler *hbs = new HeldButtonScheduler(Grab(), this, command);
hbs->Start();
}
void Trigger::WhenInactive(Command *command)
{
ReleasedButtonScheduler *rbs = new ReleasedButtonScheduler(Grab(), this, command);
rbs->Start();
void Trigger::WhenInactive(Command *command) {
ReleasedButtonScheduler *rbs =
new ReleasedButtonScheduler(Grab(), this, command);
rbs->Start();
}
void Trigger::CancelWhenActive(Command *command) {
CancelButtonScheduler *cbs = new CancelButtonScheduler(Grab(), this, command);
cbs->Start();
CancelButtonScheduler *cbs = new CancelButtonScheduler(Grab(), this, command);
cbs->Start();
}
void Trigger::ToggleWhenActive(Command *command) {
ToggleButtonScheduler *tbs = new ToggleButtonScheduler(Grab(), this, command);
tbs->Start();
ToggleButtonScheduler *tbs = new ToggleButtonScheduler(Grab(), this, command);
tbs->Start();
}
std::string Trigger::GetSmartDashboardType() const {
return "Button";
std::string Trigger::GetSmartDashboardType() const { return "Button"; }
void Trigger::InitTable(ITable *table) {
m_table = table;
if (m_table != NULL) {
m_table->PutBoolean("pressed", Get());
}
}
void Trigger::InitTable(ITable* table){
m_table = table;
if(m_table!=NULL){
m_table->PutBoolean("pressed", Get());
}
}
ITable* Trigger::GetTable() const {
return m_table;
}
ITable *Trigger::GetTable() const { return m_table; }

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -18,40 +19,34 @@ static const char *kIsParented = "isParented";
int Command::m_commandCounter = 0;
void Command::InitCommand(const char *name, double timeout)
{
m_commandID = m_commandCounter++;
m_timeout = timeout;
m_locked = false;
m_startTime = -1;
m_initialized = false;
m_running = false;
m_interruptible = true;
m_canceled = false;
m_runWhenDisabled = false;
m_parent = NULL;
m_name = name == NULL? std::string() : name;
m_table = NULL;
void Command::InitCommand(const char *name, double timeout) {
m_commandID = m_commandCounter++;
m_timeout = timeout;
m_locked = false;
m_startTime = -1;
m_initialized = false;
m_running = false;
m_interruptible = true;
m_canceled = false;
m_runWhenDisabled = false;
m_parent = NULL;
m_name = name == NULL ? std::string() : name;
m_table = NULL;
}
/**
* Creates a new command.
* The name of this command will be default.
*/
Command::Command()
{
InitCommand(NULL, -1.0);
}
Command::Command() { InitCommand(NULL, -1.0); }
/**
* Creates a new command with the given name and no timeout.
* @param name the name for this command
*/
Command::Command(const char *name)
{
if (name == NULL)
wpi_setWPIErrorWithContext(NullParameter, "name");
InitCommand(name, -1.0);
Command::Command(const char *name) {
if (name == NULL) wpi_setWPIErrorWithContext(NullParameter, "name");
InitCommand(name, -1.0);
}
/**
@@ -59,11 +54,10 @@ Command::Command(const char *name)
* @param timeout the time (in seconds) before this command "times out"
* @see Command#isTimedOut() isTimedOut()
*/
Command::Command(double timeout)
{
if (timeout < 0.0)
wpi_setWPIErrorWithContext(ParameterOutOfRange, "timeout < 0.0");
InitCommand(NULL, timeout);
Command::Command(double timeout) {
if (timeout < 0.0)
wpi_setWPIErrorWithContext(ParameterOutOfRange, "timeout < 0.0");
InitCommand(NULL, timeout);
}
/**
@@ -72,20 +66,17 @@ Command::Command(double timeout)
* @param timeout the time (in seconds) before this command "times out"
* @see Command#isTimedOut() isTimedOut()
*/
Command::Command(const char *name, double timeout)
{
if (name == NULL)
wpi_setWPIErrorWithContext(NullParameter, "name");
if (timeout < 0.0)
wpi_setWPIErrorWithContext(ParameterOutOfRange, "timeout < 0.0");
InitCommand(name, timeout);
Command::Command(const char *name, double timeout) {
if (name == NULL) wpi_setWPIErrorWithContext(NullParameter, "name");
if (timeout < 0.0)
wpi_setWPIErrorWithContext(ParameterOutOfRange, "timeout < 0.0");
InitCommand(name, timeout);
}
Command::~Command()
{//TODO deal with cleaning up all listeners
/*if (m_table != NULL){
m_table->RemoveChangeListener(kRunning, this);
}*/
Command::~Command() { // TODO deal with cleaning up all listeners
/*if (m_table != NULL){
m_table->RemoveChangeListener(kRunning, this);
}*/
}
/**
@@ -93,21 +84,18 @@ Command::~Command()
* The ID is a unique sequence number that is incremented for each command.
* @return the ID of this command
*/
int Command::GetID() const {
return m_commandID;
}
int Command::GetID() const { return m_commandID; }
/**
* Sets the timeout of this command.
* @param timeout the timeout (in seconds)
* @see Command#isTimedOut() isTimedOut()
*/
void Command::SetTimeout(double timeout)
{
if (timeout < 0.0)
wpi_setWPIErrorWithContext(ParameterOutOfRange, "timeout < 0.0");
else
m_timeout = timeout;
void Command::SetTimeout(double timeout) {
if (timeout < 0.0)
wpi_setWPIErrorWithContext(ParameterOutOfRange, "timeout < 0.0");
else
m_timeout = timeout;
}
/**
@@ -115,192 +103,171 @@ void Command::SetTimeout(double timeout)
* This function will work even if there is no specified timeout.
* @return the time since this command was initialized (in seconds).
*/
double Command::TimeSinceInitialized() const
{
if (m_startTime < 0.0)
return 0.0;
else
return Timer::GetFPGATimestamp() - m_startTime;
double Command::TimeSinceInitialized() const {
if (m_startTime < 0.0)
return 0.0;
else
return Timer::GetFPGATimestamp() - m_startTime;
}
/**
* This method specifies that the given {@link Subsystem} is used by this command.
* This method specifies that the given {@link Subsystem} is used by this
* command.
* This method is crucial to the functioning of the Command System in general.
*
* <p>Note that the recommended way to call this method is in the constructor.</p>
* <p>Note that the recommended way to call this method is in the
* constructor.</p>
*
* @param subsystem the {@link Subsystem} required
* @see Subsystem
*/
void Command::Requires(Subsystem *subsystem)
{
if (!AssertUnlocked("Can not add new requirement to command"))
return;
void Command::Requires(Subsystem *subsystem) {
if (!AssertUnlocked("Can not add new requirement to command")) return;
if (subsystem != NULL)
m_requirements.insert(subsystem);
else
wpi_setWPIErrorWithContext(NullParameter, "subsystem");
if (subsystem != NULL)
m_requirements.insert(subsystem);
else
wpi_setWPIErrorWithContext(NullParameter, "subsystem");
}
/**
* Called when the command has been removed.
* This will call {@link Command#interrupted() interrupted()} or {@link Command#end() end()}.
* This will call {@link Command#interrupted() interrupted()} or {@link
* Command#end() end()}.
*/
void Command::Removed()
{
if (m_initialized)
{
if (IsCanceled())
{
Interrupted();
_Interrupted();
}
else
{
End();
_End();
}
}
m_initialized = false;
m_canceled = false;
m_running = false;
if (m_table != NULL)
m_table->PutBoolean(kRunning, false);
void Command::Removed() {
if (m_initialized) {
if (IsCanceled()) {
Interrupted();
_Interrupted();
} else {
End();
_End();
}
}
m_initialized = false;
m_canceled = false;
m_running = false;
if (m_table != NULL) m_table->PutBoolean(kRunning, false);
}
/**
* Starts up the command. Gets the command ready to start.
* <p>Note that the command will eventually start, however it will not necessarily
* do so immediately, and may in fact be canceled before initialize is even called.</p>
* <p>Note that the command will eventually start, however it will not
* necessarily
* do so immediately, and may in fact be canceled before initialize is even
* called.</p>
*/
void Command::Start()
{
LockChanges();
if (m_parent != NULL)
wpi_setWPIErrorWithContext(CommandIllegalUse, "Can not start a command that is part of a command group");
void Command::Start() {
LockChanges();
if (m_parent != NULL)
wpi_setWPIErrorWithContext(
CommandIllegalUse,
"Can not start a command that is part of a command group");
Scheduler::GetInstance()->AddCommand(this);
Scheduler::GetInstance()->AddCommand(this);
}
/**
* The run method is used internally to actually run the commands.
* @return whether or not the command should stay within the {@link Scheduler}.
*/
bool Command::Run()
{
if (!m_runWhenDisabled && m_parent == NULL && RobotState::IsDisabled())
Cancel();
bool Command::Run() {
if (!m_runWhenDisabled && m_parent == NULL && RobotState::IsDisabled())
Cancel();
if (IsCanceled())
return false;
if (IsCanceled()) return false;
if (!m_initialized)
{
m_initialized = true;
StartTiming();
_Initialize();
Initialize();
}
_Execute();
Execute();
return !IsFinished();
if (!m_initialized) {
m_initialized = true;
StartTiming();
_Initialize();
Initialize();
}
_Execute();
Execute();
return !IsFinished();
}
void Command::_Initialize()
{
}
void Command::_Initialize() {}
void Command::_Interrupted()
{
}
void Command::_Interrupted() {}
void Command::_Execute()
{
}
void Command::_Execute() {}
void Command::_End()
{
}
void Command::_End() {}
/**
* Called to indicate that the timer should start.
* This is called right before {@link Command#initialize() initialize()} is, inside the
* This is called right before {@link Command#initialize() initialize()} is,
* inside the
* {@link Command#run() run()} method.
*/
void Command::StartTiming()
{
m_startTime = Timer::GetFPGATimestamp();
}
void Command::StartTiming() { m_startTime = Timer::GetFPGATimestamp(); }
/**
* Returns whether or not the {@link Command#timeSinceInitialized() timeSinceInitialized()}
* method returns a number which is greater than or equal to the timeout for the command.
* Returns whether or not the {@link Command#timeSinceInitialized()
* timeSinceInitialized()}
* method returns a number which is greater than or equal to the timeout for the
* command.
* If there is no timeout, this will always return false.
* @return whether the time has expired
*/
bool Command::IsTimedOut() const
{
return m_timeout != -1 && TimeSinceInitialized() >= m_timeout;
bool Command::IsTimedOut() const {
return m_timeout != -1 && TimeSinceInitialized() >= m_timeout;
}
/**
* Returns the requirements (as an std::set of {@link Subsystem Subsystems} pointers) of this command
* @return the requirements (as an std::set of {@link Subsystem Subsystems} pointers) of this command
* Returns the requirements (as an std::set of {@link Subsystem Subsystems}
* pointers) of this command
* @return the requirements (as an std::set of {@link Subsystem Subsystems}
* pointers) of this command
*/
Command::SubsystemSet Command::GetRequirements() const
{
return m_requirements;
Command::SubsystemSet Command::GetRequirements() const {
return m_requirements;
}
/**
* Prevents further changes from being made
*/
void Command::LockChanges()
{
m_locked = true;
}
void Command::LockChanges() { m_locked = true; }
/**
* If changes are locked, then this will generate a CommandIllegalUse error.
* @param message the message to report on error (it is appended by a default message)
* @param message the message to report on error (it is appended by a default
* message)
* @return true if assert passed, false if assert failed
*/
bool Command::AssertUnlocked(const char *message)
{
if (m_locked)
{
char buf[128];
snprintf(buf, 128, "%s after being started or being added to a command group", message);
wpi_setWPIErrorWithContext(CommandIllegalUse, buf);
return false;
}
return true;
bool Command::AssertUnlocked(const char *message) {
if (m_locked) {
char buf[128];
snprintf(buf, 128,
"%s after being started or being added to a command group",
message);
wpi_setWPIErrorWithContext(CommandIllegalUse, buf);
return false;
}
return true;
}
/**
* Sets the parent of this command. No actual change is made to the group.
* @param parent the parent
*/
void Command::SetParent(CommandGroup *parent)
{
if (parent == NULL)
{
wpi_setWPIErrorWithContext(NullParameter, "parent");
}
else if (m_parent != NULL)
{
wpi_setWPIErrorWithContext(CommandIllegalUse, "Can not give command to a command group after already being put in a command group");
}
else
{
LockChanges();
m_parent = parent;
if (m_table != NULL)
{
m_table->PutBoolean(kIsParented, true);
}
}
void Command::SetParent(CommandGroup *parent) {
if (parent == NULL) {
wpi_setWPIErrorWithContext(NullParameter, "parent");
} else if (m_parent != NULL) {
wpi_setWPIErrorWithContext(CommandIllegalUse,
"Can not give command to a command group after "
"already being put in a command group");
} else {
LockChanges();
m_parent = parent;
if (m_table != NULL) {
m_table->PutBoolean(kIsParented, true);
}
}
}
/**
@@ -311,15 +278,14 @@ void Command::SetParent(CommandGroup *parent)
* run() is called (multiple times potentially)
* removed() is called
*
* It is very important that startRunning and removed be called in order or some assumptions
* It is very important that startRunning and removed be called in order or some
* assumptions
* of the code will be broken.
*/
void Command::StartRunning()
{
m_running = true;
m_startTime = -1;
if (m_table != NULL)
m_table->PutBoolean(kRunning, true);
void Command::StartRunning() {
m_running = true;
m_startTime = -1;
if (m_table != NULL) m_table->PutBoolean(kRunning, true);
}
/**
@@ -328,62 +294,55 @@ void Command::StartRunning()
* not have yet called {@link Command#interrupted()}.
* @return whether or not the command is running
*/
bool Command::IsRunning() const
{
return m_running;
}
bool Command::IsRunning() const { return m_running; }
/**
* This will cancel the current command.
* <p>This will cancel the current command eventually. It can be called multiple times.
* And it can be called when the command is not running. If the command is running though,
* <p>This will cancel the current command eventually. It can be called
* multiple times.
* And it can be called when the command is not running. If the command is
* running though,
* then the command will be marked as canceled and eventually removed.</p>
* <p>A command can not be canceled
* if it is a part of a command group, you must cancel the command group instead.</p>
* if it is a part of a command group, you must cancel the command group
* instead.</p>
*/
void Command::Cancel()
{
if (m_parent != NULL)
wpi_setWPIErrorWithContext(CommandIllegalUse, "Can not cancel a command that is part of a command group");
void Command::Cancel() {
if (m_parent != NULL)
wpi_setWPIErrorWithContext(
CommandIllegalUse,
"Can not cancel a command that is part of a command group");
_Cancel();
_Cancel();
}
/**
* This works like cancel(), except that it doesn't throw an exception if it is a part
* This works like cancel(), except that it doesn't throw an exception if it is
* a part
* of a command group. Should only be called by the parent command group.
*/
void Command::_Cancel()
{
if (IsRunning())
m_canceled = true;
void Command::_Cancel() {
if (IsRunning()) m_canceled = true;
}
/**
* Returns whether or not this has been canceled.
* @return whether or not this has been canceled
*/
bool Command::IsCanceled() const
{
return m_canceled;
}
bool Command::IsCanceled() const { return m_canceled; }
/**
* Returns whether or not this command can be interrupted.
* @return whether or not this command can be interrupted
*/
bool Command::IsInterruptible() const
{
return m_interruptible;
}
bool Command::IsInterruptible() const { return m_interruptible; }
/**
* Sets whether or not this command can be interrupted.
* @param interruptible whether or not this command can be interrupted
*/
void Command::SetInterruptible(bool interruptible)
{
m_interruptible = interruptible;
void Command::SetInterruptible(bool interruptible) {
m_interruptible = interruptible;
}
/**
@@ -391,80 +350,63 @@ void Command::SetInterruptible(bool interruptible)
* @param system the system
* @return whether or not the subsystem is required (false if given NULL)
*/
bool Command::DoesRequire(Subsystem *system) const
{
return m_requirements.count(system) > 0;
bool Command::DoesRequire(Subsystem *system) const {
return m_requirements.count(system) > 0;
}
/**
* Returns the {@link CommandGroup} that this command is a part of.
* Will return null if this {@link Command} is not in a group.
* @return the {@link CommandGroup} that this command is a part of (or null if not in group)
* @return the {@link CommandGroup} that this command is a part of (or null if
* not in group)
*/
CommandGroup *Command::GetGroup() const
{
return m_parent;
}
CommandGroup *Command::GetGroup() const { return m_parent; }
/**
* Sets whether or not this {@link Command} should run when the robot is disabled.
* Sets whether or not this {@link Command} should run when the robot is
* disabled.
*
* <p>By default a command will not run when the robot is disabled, and will in fact be canceled.</p>
* <p>By default a command will not run when the robot is disabled, and will in
* fact be canceled.</p>
* @param run whether or not this command should run when the robot is disabled
*/
void Command::SetRunWhenDisabled(bool run)
{
m_runWhenDisabled = run;
}
void Command::SetRunWhenDisabled(bool run) { m_runWhenDisabled = run; }
/**
* Returns whether or not this {@link Command} will run when the robot is disabled, or if it will cancel itself.
* @return whether or not this {@link Command} will run when the robot is disabled, or if it will cancel itself
* Returns whether or not this {@link Command} will run when the robot is
* disabled, or if it will cancel itself.
* @return whether or not this {@link Command} will run when the robot is
* disabled, or if it will cancel itself
*/
bool Command::WillRunWhenDisabled() const
{
return m_runWhenDisabled;
bool Command::WillRunWhenDisabled() const { return m_runWhenDisabled; }
std::string Command::GetName() {
if (m_name.length() == 0) {
m_name = std::string("Command_") + std::string(typeid(*this).name());
}
return m_name;
}
std::string Command::GetName()
{
if (m_name.length() == 0)
{
m_name = std::string("Command_") + std::string(typeid(*this).name());
}
return m_name;
std::string Command::GetSmartDashboardType() const { return "Command"; }
void Command::InitTable(ITable *table) {
if (m_table != NULL) m_table->RemoveTableListener(this);
m_table = table;
if (m_table != NULL) {
m_table->PutString(kName, GetName());
m_table->PutBoolean(kRunning, IsRunning());
m_table->PutBoolean(kIsParented, m_parent != NULL);
m_table->AddTableListener(kRunning, this, false);
}
}
std::string Command::GetSmartDashboardType() const
{
return "Command";
}
ITable *Command::GetTable() const { return m_table; }
void Command::InitTable(ITable* table)
{
if(m_table!=NULL)
m_table->RemoveTableListener(this);
m_table = table;
if(m_table!=NULL){
m_table->PutString(kName, GetName());
m_table->PutBoolean(kRunning, IsRunning());
m_table->PutBoolean(kIsParented, m_parent != NULL);
m_table->AddTableListener(kRunning, this, false);
}
}
ITable* Command::GetTable() const {
return m_table;
}
void Command::ValueChanged(ITable* source, const std::string& key, EntryValue value, bool isNew)
{
if (value.b){
if(!IsRunning())
Start();
}
else{
if(IsRunning())
Cancel();
}
void Command::ValueChanged(ITable *source, const std::string &key,
EntryValue value, bool isNew) {
if (value.b) {
if (!IsRunning()) Start();
} else {
if (IsRunning()) Cancel();
}
}

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -10,67 +11,66 @@
/**
* Creates a new {@link CommandGroup CommandGroup}.
*/
CommandGroup::CommandGroup()
{
m_currentCommandIndex = -1;
}
CommandGroup::CommandGroup() { m_currentCommandIndex = -1; }
/**
* Creates a new {@link CommandGroup CommandGroup} with the given name.
* @param name the name for this command group
*/
CommandGroup::CommandGroup(const char *name) :
Command(name)
{
m_currentCommandIndex = -1;
CommandGroup::CommandGroup(const char *name) : Command(name) {
m_currentCommandIndex = -1;
}
CommandGroup::~CommandGroup()
{
}
CommandGroup::~CommandGroup() {}
/**
* Adds a new {@link Command Command} to the group. The {@link Command Command} will be started after
* Adds a new {@link Command Command} to the group. The {@link Command Command}
* will be started after
* all the previously added {@link Command Commands}.
*
* <p>Note that any requirements the given {@link Command Command} has will be added to the
* group. For this reason, a {@link Command Command's} requirements can not be changed after
* <p>Note that any requirements the given {@link Command Command} has will be
* added to the
* group. For this reason, a {@link Command Command's} requirements can not be
* changed after
* being added to a group.</p>
*
* <p>It is recommended that this method be called in the constructor.</p>
*
*
* @param command The {@link Command Command} to be added
*/
void CommandGroup::AddSequential(Command *command)
{
if (command == NULL)
{
wpi_setWPIErrorWithContext(NullParameter, "command");
return;
}
if (!AssertUnlocked("Cannot add new command to command group"))
return;
void CommandGroup::AddSequential(Command *command) {
if (command == NULL) {
wpi_setWPIErrorWithContext(NullParameter, "command");
return;
}
if (!AssertUnlocked("Cannot add new command to command group")) return;
command->SetParent(this);
command->SetParent(this);
m_commands.push_back(CommandGroupEntry(command, CommandGroupEntry::kSequence_InSequence));
// Iterate through command->GetRequirements() and call Requires() on each required subsystem
Command::SubsystemSet requirements = command->GetRequirements();
Command::SubsystemSet::iterator iter = requirements.begin();
for (; iter != requirements.end(); iter++)
Requires(*iter);
m_commands.push_back(
CommandGroupEntry(command, CommandGroupEntry::kSequence_InSequence));
// Iterate through command->GetRequirements() and call Requires() on each
// required subsystem
Command::SubsystemSet requirements = command->GetRequirements();
Command::SubsystemSet::iterator iter = requirements.begin();
for (; iter != requirements.end(); iter++) Requires(*iter);
}
/**
* Adds a new {@link Command Command} to the group with a given timeout.
* The {@link Command Command} will be started after all the previously added commands.
* The {@link Command Command} will be started after all the previously added
* commands.
*
* <p>Once the {@link Command Command} is started, it will be run until it finishes or the time
* expires, whichever is sooner. Note that the given {@link Command Command} will have no
* <p>Once the {@link Command Command} is started, it will be run until it
* finishes or the time
* expires, whichever is sooner. Note that the given {@link Command Command}
* will have no
* knowledge that it is on a timer.</p>
*
* <p>Note that any requirements the given {@link Command Command} has will be added to the
* group. For this reason, a {@link Command Command's} requirements can not be changed after
* <p>Note that any requirements the given {@link Command Command} has will be
* added to the
* group. For this reason, a {@link Command Command's} requirements can not be
* changed after
* being added to a group.</p>
*
* <p>It is recommended that this method be called in the constructor.</p>
@@ -78,87 +78,97 @@ void CommandGroup::AddSequential(Command *command)
* @param command The {@link Command Command} to be added
* @param timeout The timeout (in seconds)
*/
void CommandGroup::AddSequential(Command *command, double timeout)
{
if (command == NULL)
{
wpi_setWPIErrorWithContext(NullParameter, "command");
return;
}
if (!AssertUnlocked("Cannot add new command to command group"))
return;
if (timeout < 0.0)
{
wpi_setWPIErrorWithContext(ParameterOutOfRange, "timeout < 0.0");
return;
}
void CommandGroup::AddSequential(Command *command, double timeout) {
if (command == NULL) {
wpi_setWPIErrorWithContext(NullParameter, "command");
return;
}
if (!AssertUnlocked("Cannot add new command to command group")) return;
if (timeout < 0.0) {
wpi_setWPIErrorWithContext(ParameterOutOfRange, "timeout < 0.0");
return;
}
command->SetParent(this);
command->SetParent(this);
m_commands.push_back(CommandGroupEntry(command, CommandGroupEntry::kSequence_InSequence, timeout));
// Iterate through command->GetRequirements() and call Requires() on each required subsystem
Command::SubsystemSet requirements = command->GetRequirements();
Command::SubsystemSet::iterator iter = requirements.begin();
for (; iter != requirements.end(); iter++)
Requires(*iter);
m_commands.push_back(CommandGroupEntry(
command, CommandGroupEntry::kSequence_InSequence, timeout));
// Iterate through command->GetRequirements() and call Requires() on each
// required subsystem
Command::SubsystemSet requirements = command->GetRequirements();
Command::SubsystemSet::iterator iter = requirements.begin();
for (; iter != requirements.end(); iter++) Requires(*iter);
}
/**
* Adds a new child {@link Command} to the group. The {@link Command} will be started after
* Adds a new child {@link Command} to the group. The {@link Command} will be
* started after
* all the previously added {@link Command Commands}.
*
* <p>Instead of waiting for the child to finish, a {@link CommandGroup} will have it
* run at the same time as the subsequent {@link Command Commands}. The child will run until either
* <p>Instead of waiting for the child to finish, a {@link CommandGroup} will
* have it
* run at the same time as the subsequent {@link Command Commands}. The child
* will run until either
* it finishes, a new child with conflicting requirements is started, or
* the main sequence runs a {@link Command} with conflicting requirements. In the latter
* the main sequence runs a {@link Command} with conflicting requirements. In
* the latter
* two cases, the child will be canceled even if it says it can't be
* interrupted.</p>
*
* <p>Note that any requirements the given {@link Command Command} has will be added to the
* group. For this reason, a {@link Command Command's} requirements can not be changed after
* <p>Note that any requirements the given {@link Command Command} has will be
* added to the
* group. For this reason, a {@link Command Command's} requirements can not be
* changed after
* being added to a group.</p>
*
* <p>It is recommended that this method be called in the constructor.</p>
*
* @param command The command to be added
*/
void CommandGroup::AddParallel(Command *command)
{
if (command == NULL)
{
wpi_setWPIErrorWithContext(NullParameter, "command");
return;
}
if (!AssertUnlocked("Cannot add new command to command group"))
return;
void CommandGroup::AddParallel(Command *command) {
if (command == NULL) {
wpi_setWPIErrorWithContext(NullParameter, "command");
return;
}
if (!AssertUnlocked("Cannot add new command to command group")) return;
command->SetParent(this);
command->SetParent(this);
m_commands.push_back(CommandGroupEntry(command, CommandGroupEntry::kSequence_BranchChild));
// Iterate through command->GetRequirements() and call Requires() on each required subsystem
Command::SubsystemSet requirements = command->GetRequirements();
Command::SubsystemSet::iterator iter = requirements.begin();
for (; iter != requirements.end(); iter++)
Requires(*iter);
m_commands.push_back(
CommandGroupEntry(command, CommandGroupEntry::kSequence_BranchChild));
// Iterate through command->GetRequirements() and call Requires() on each
// required subsystem
Command::SubsystemSet requirements = command->GetRequirements();
Command::SubsystemSet::iterator iter = requirements.begin();
for (; iter != requirements.end(); iter++) Requires(*iter);
}
/**
* Adds a new child {@link Command} to the group with the given timeout. The {@link Command} will be started after
* Adds a new child {@link Command} to the group with the given timeout. The
* {@link Command} will be started after
* all the previously added {@link Command Commands}.
*
* <p>Once the {@link Command Command} is started, it will run until it finishes, is interrupted,
* or the time expires, whichever is sooner. Note that the given {@link Command Command} will have no
* <p>Once the {@link Command Command} is started, it will run until it
* finishes, is interrupted,
* or the time expires, whichever is sooner. Note that the given {@link Command
* Command} will have no
* knowledge that it is on a timer.</p>
*
* <p>Instead of waiting for the child to finish, a {@link CommandGroup} will have it
* run at the same time as the subsequent {@link Command Commands}. The child will run until either
* it finishes, the timeout expires, a new child with conflicting requirements is started, or
* the main sequence runs a {@link Command} with conflicting requirements. In the latter
* <p>Instead of waiting for the child to finish, a {@link CommandGroup} will
* have it
* run at the same time as the subsequent {@link Command Commands}. The child
* will run until either
* it finishes, the timeout expires, a new child with conflicting requirements
* is started, or
* the main sequence runs a {@link Command} with conflicting requirements. In
* the latter
* two cases, the child will be canceled even if it says it can't be
* interrupted.</p>
*
* <p>Note that any requirements the given {@link Command Command} has will be added to the
* group. For this reason, a {@link Command Command's} requirements can not be changed after
* <p>Note that any requirements the given {@link Command Command} has will be
* added to the
* group. For this reason, a {@link Command Command's} requirements can not be
* changed after
* being added to a group.</p>
*
* <p>It is recommended that this method be called in the constructor.</p>
@@ -166,218 +176,172 @@ void CommandGroup::AddParallel(Command *command)
* @param command The command to be added
* @param timeout The timeout (in seconds)
*/
void CommandGroup::AddParallel(Command *command, double timeout)
{
if (command == NULL)
{
wpi_setWPIErrorWithContext(NullParameter, "command");
return;
}
if (!AssertUnlocked("Cannot add new command to command group"))
return;
if (timeout < 0.0)
{
wpi_setWPIErrorWithContext(ParameterOutOfRange, "timeout < 0.0");
return;
}
void CommandGroup::AddParallel(Command *command, double timeout) {
if (command == NULL) {
wpi_setWPIErrorWithContext(NullParameter, "command");
return;
}
if (!AssertUnlocked("Cannot add new command to command group")) return;
if (timeout < 0.0) {
wpi_setWPIErrorWithContext(ParameterOutOfRange, "timeout < 0.0");
return;
}
command->SetParent(this);
command->SetParent(this);
m_commands.push_back(CommandGroupEntry(command, CommandGroupEntry::kSequence_BranchChild, timeout));
// Iterate through command->GetRequirements() and call Requires() on each required subsystem
Command::SubsystemSet requirements = command->GetRequirements();
Command::SubsystemSet::iterator iter = requirements.begin();
for (; iter != requirements.end(); iter++)
Requires(*iter);
m_commands.push_back(CommandGroupEntry(
command, CommandGroupEntry::kSequence_BranchChild, timeout));
// Iterate through command->GetRequirements() and call Requires() on each
// required subsystem
Command::SubsystemSet requirements = command->GetRequirements();
Command::SubsystemSet::iterator iter = requirements.begin();
for (; iter != requirements.end(); iter++) Requires(*iter);
}
void CommandGroup::_Initialize()
{
m_currentCommandIndex = -1;
void CommandGroup::_Initialize() { m_currentCommandIndex = -1; }
void CommandGroup::_Execute() {
CommandGroupEntry entry;
Command *cmd = NULL;
bool firstRun = false;
if (m_currentCommandIndex == -1) {
firstRun = true;
m_currentCommandIndex = 0;
}
while ((unsigned)m_currentCommandIndex < m_commands.size()) {
if (cmd != NULL) {
if (entry.IsTimedOut()) cmd->_Cancel();
if (cmd->Run()) {
break;
} else {
cmd->Removed();
m_currentCommandIndex++;
firstRun = true;
cmd = NULL;
continue;
}
}
entry = m_commands[m_currentCommandIndex];
cmd = NULL;
switch (entry.m_state) {
case CommandGroupEntry::kSequence_InSequence:
cmd = entry.m_command;
if (firstRun) {
cmd->StartRunning();
CancelConflicts(cmd);
firstRun = false;
}
break;
case CommandGroupEntry::kSequence_BranchPeer:
m_currentCommandIndex++;
entry.m_command->Start();
break;
case CommandGroupEntry::kSequence_BranchChild:
m_currentCommandIndex++;
CancelConflicts(entry.m_command);
entry.m_command->StartRunning();
m_children.push_back(entry);
break;
}
}
// Run Children
CommandList::iterator iter = m_children.begin();
for (; iter != m_children.end();) {
entry = *iter;
Command *child = entry.m_command;
if (entry.IsTimedOut()) child->_Cancel();
if (!child->Run()) {
child->Removed();
iter = m_children.erase(iter);
} else {
iter++;
}
}
}
void CommandGroup::_Execute()
{
CommandGroupEntry entry;
Command *cmd = NULL;
bool firstRun = false;
void CommandGroup::_End() {
// Theoretically, we don't have to check this, but we do if teams override the
// IsFinished method
if (m_currentCommandIndex != -1 &&
(unsigned)m_currentCommandIndex < m_commands.size()) {
Command *cmd = m_commands[m_currentCommandIndex].m_command;
cmd->_Cancel();
cmd->Removed();
}
if (m_currentCommandIndex == -1)
{
firstRun = true;
m_currentCommandIndex = 0;
}
while ((unsigned)m_currentCommandIndex < m_commands.size())
{
if (cmd != NULL)
{
if (entry.IsTimedOut())
cmd->_Cancel();
if (cmd->Run())
{
break;
}
else
{
cmd->Removed();
m_currentCommandIndex++;
firstRun = true;
cmd = NULL;
continue;
}
}
entry = m_commands[m_currentCommandIndex];
cmd = NULL;
switch (entry.m_state)
{
case CommandGroupEntry::kSequence_InSequence:
cmd = entry.m_command;
if (firstRun)
{
cmd->StartRunning();
CancelConflicts(cmd);
firstRun = false;
}
break;
case CommandGroupEntry::kSequence_BranchPeer:
m_currentCommandIndex++;
entry.m_command->Start();
break;
case CommandGroupEntry::kSequence_BranchChild:
m_currentCommandIndex++;
CancelConflicts(entry.m_command);
entry.m_command->StartRunning();
m_children.push_back(entry);
break;
}
}
// Run Children
CommandList::iterator iter = m_children.begin();
for (; iter != m_children.end();)
{
entry = *iter;
Command *child = entry.m_command;
if (entry.IsTimedOut())
child->_Cancel();
if (!child->Run())
{
child->Removed();
iter = m_children.erase(iter);
}
else
{
iter++;
}
}
CommandList::iterator iter = m_children.begin();
for (; iter != m_children.end(); iter++) {
Command *cmd = iter->m_command;
cmd->_Cancel();
cmd->Removed();
}
m_children.clear();
}
void CommandGroup::_End()
{
// Theoretically, we don't have to check this, but we do if teams override the IsFinished method
if (m_currentCommandIndex != -1 && (unsigned)m_currentCommandIndex < m_commands.size())
{
Command *cmd = m_commands[m_currentCommandIndex].m_command;
cmd->_Cancel();
cmd->Removed();
}
CommandList::iterator iter = m_children.begin();
for (; iter != m_children.end(); iter++)
{
Command *cmd = iter->m_command;
cmd->_Cancel();
cmd->Removed();
}
m_children.clear();
}
void CommandGroup::_Interrupted()
{
_End();
}
void CommandGroup::_Interrupted() { _End(); }
// Can be overwritten by teams
void CommandGroup::Initialize()
{
}
void CommandGroup::Initialize() {}
// Can be overwritten by teams
void CommandGroup::Execute()
{
}
void CommandGroup::Execute() {}
// Can be overwritten by teams
void CommandGroup::End()
{
}
void CommandGroup::End() {}
// Can be overwritten by teams
void CommandGroup::Interrupted()
{
void CommandGroup::Interrupted() {}
bool CommandGroup::IsFinished() {
return (unsigned)m_currentCommandIndex >= m_commands.size() &&
m_children.empty();
}
bool CommandGroup::IsFinished()
{
return (unsigned)m_currentCommandIndex >= m_commands.size() && m_children.empty();
bool CommandGroup::IsInterruptible() const {
if (!Command::IsInterruptible()) return false;
if (m_currentCommandIndex != -1 &&
(unsigned)m_currentCommandIndex < m_commands.size()) {
Command *cmd = m_commands[m_currentCommandIndex].m_command;
if (!cmd->IsInterruptible()) return false;
}
CommandList::const_iterator iter = m_children.cbegin();
for (; iter != m_children.cend(); iter++) {
if (!iter->m_command->IsInterruptible()) return false;
}
return true;
}
bool CommandGroup::IsInterruptible() const
{
if (!Command::IsInterruptible())
return false;
void CommandGroup::CancelConflicts(Command *command) {
CommandList::iterator childIter = m_children.begin();
for (; childIter != m_children.end();) {
Command *child = childIter->m_command;
bool erased = false;
if (m_currentCommandIndex != -1 && (unsigned)m_currentCommandIndex < m_commands.size())
{
Command *cmd = m_commands[m_currentCommandIndex].m_command;
if (!cmd->IsInterruptible())
return false;
}
CommandList::const_iterator iter = m_children.cbegin();
for (; iter != m_children.cend(); iter++)
{
if (!iter->m_command->IsInterruptible())
return false;
}
return true;
Command::SubsystemSet requirements = command->GetRequirements();
Command::SubsystemSet::iterator requirementIter = requirements.begin();
for (; requirementIter != requirements.end(); requirementIter++) {
if (child->DoesRequire(*requirementIter)) {
child->_Cancel();
child->Removed();
childIter = m_children.erase(childIter);
erased = true;
break;
}
}
if (!erased) childIter++;
}
}
void CommandGroup::CancelConflicts(Command *command)
{
CommandList::iterator childIter = m_children.begin();
for (; childIter != m_children.end();)
{
Command *child = childIter->m_command;
bool erased = false;
Command::SubsystemSet requirements = command->GetRequirements();
Command::SubsystemSet::iterator requirementIter = requirements.begin();
for (; requirementIter != requirements.end(); requirementIter++)
{
if (child->DoesRequire(*requirementIter))
{
child->_Cancel();
child->Removed();
childIter = m_children.erase(childIter);
erased = true;
break;
}
}
if (!erased)
childIter++;
}
}
int CommandGroup::GetSize() const
{
return m_children.size();
}
int CommandGroup::GetSize() const { return m_children.size(); }

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -8,33 +9,19 @@
#include "Commands/Command.h"
CommandGroupEntry::CommandGroupEntry() :
m_timeout(-1.0),
m_command(NULL),
m_state(kSequence_InSequence)
{
}
CommandGroupEntry::CommandGroupEntry()
: m_timeout(-1.0), m_command(NULL), m_state(kSequence_InSequence) {}
CommandGroupEntry::CommandGroupEntry(Command *command, Sequence state) :
m_timeout(-1.0),
m_command(command),
m_state(state)
{
}
CommandGroupEntry::CommandGroupEntry(Command *command, Sequence state)
: m_timeout(-1.0), m_command(command), m_state(state) {}
CommandGroupEntry::CommandGroupEntry(Command *command, Sequence state, double timeout) :
m_timeout(timeout),
m_command(command),
m_state(state)
{
}
CommandGroupEntry::CommandGroupEntry(Command *command, Sequence state,
double timeout)
: m_timeout(timeout), m_command(command), m_state(state) {}
bool CommandGroupEntry::IsTimedOut() const
{
if (m_timeout < 0.0)
return false;
double time = m_command->TimeSinceInitialized();
if (time == 0.0)
return false;
return time >= m_timeout;
bool CommandGroupEntry::IsTimedOut() const {
if (m_timeout < 0.0) return false;
double time = m_command->TimeSinceInitialized();
if (time == 0.0) return false;
return time >= m_timeout;
}

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -9,98 +10,63 @@
#include "PIDController.h"
#include "float.h"
PIDCommand::PIDCommand(const char *name, double p, double i, double d, double f, double period) :
Command(name)
{
m_controller = new PIDController(p, i, d, this, this, period);
PIDCommand::PIDCommand(const char *name, double p, double i, double d, double f,
double period)
: Command(name) {
m_controller = new PIDController(p, i, d, this, this, period);
}
PIDCommand::PIDCommand(double p, double i, double d, double f, double period)
{
m_controller = new PIDController(p, i, d, f, this, this, period);
PIDCommand::PIDCommand(double p, double i, double d, double f, double period) {
m_controller = new PIDController(p, i, d, f, this, this, period);
}
PIDCommand::PIDCommand(const char *name, double p, double i, double d) :
Command(name)
{
m_controller = new PIDController(p, i, d, this, this);
PIDCommand::PIDCommand(const char *name, double p, double i, double d)
: Command(name) {
m_controller = new PIDController(p, i, d, this, this);
}
PIDCommand::PIDCommand(const char *name, double p, double i, double d, double period) :
Command(name)
{
m_controller = new PIDController(p, i, d, this, this, period);
PIDCommand::PIDCommand(const char *name, double p, double i, double d,
double period)
: Command(name) {
m_controller = new PIDController(p, i, d, this, this, period);
}
PIDCommand::PIDCommand(double p, double i, double d)
{
m_controller = new PIDController(p, i, d, this, this);
PIDCommand::PIDCommand(double p, double i, double d) {
m_controller = new PIDController(p, i, d, this, this);
}
PIDCommand::PIDCommand(double p, double i, double d, double period)
{
m_controller = new PIDController(p, i, d, this, this, period);
PIDCommand::PIDCommand(double p, double i, double d, double period) {
m_controller = new PIDController(p, i, d, this, this, period);
}
PIDCommand::~PIDCommand()
{
delete m_controller;
PIDCommand::~PIDCommand() { delete m_controller; }
void PIDCommand::_Initialize() { m_controller->Enable(); }
void PIDCommand::_End() { m_controller->Disable(); }
void PIDCommand::_Interrupted() { _End(); }
void PIDCommand::SetSetpointRelative(double deltaSetpoint) {
SetSetpoint(GetSetpoint() + deltaSetpoint);
}
void PIDCommand::_Initialize()
{
m_controller->Enable();
void PIDCommand::PIDWrite(float output) { UsePIDOutput(output); }
double PIDCommand::PIDGet() const { return ReturnPIDInput(); }
PIDController *PIDCommand::GetPIDController() const { return m_controller; }
void PIDCommand::SetSetpoint(double setpoint) {
m_controller->SetSetpoint(setpoint);
}
void PIDCommand::_End()
{
m_controller->Disable();
}
double PIDCommand::GetSetpoint() const { return m_controller->GetSetpoint(); }
void PIDCommand::_Interrupted()
{
_End();
}
double PIDCommand::GetPosition() const { return ReturnPIDInput(); }
void PIDCommand::SetSetpointRelative(double deltaSetpoint)
{
SetSetpoint(GetSetpoint() + deltaSetpoint);
}
void PIDCommand::PIDWrite(float output)
{
UsePIDOutput(output);
}
double PIDCommand::PIDGet() const
{
return ReturnPIDInput();
}
PIDController *PIDCommand::GetPIDController() const
{
return m_controller;
}
void PIDCommand::SetSetpoint(double setpoint)
{
m_controller->SetSetpoint(setpoint);
}
double PIDCommand::GetSetpoint() const
{
return m_controller->GetSetpoint();
}
double PIDCommand::GetPosition() const
{
return ReturnPIDInput();
}
std::string PIDCommand::GetSmartDashboardType() const {
return "PIDCommand";
}
void PIDCommand::InitTable(ITable* table){
m_controller->InitTable(table);
Command::InitTable(table);
std::string PIDCommand::GetSmartDashboardType() const { return "PIDCommand"; }
void PIDCommand::InitTable(ITable *table) {
m_controller->InitTable(table);
Command::InitTable(table);
}

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -9,34 +10,36 @@
#include "float.h"
/**
* Instantiates a {@link PIDSubsystem} that will use the given p, i and d values.
* Instantiates a {@link PIDSubsystem} that will use the given p, i and d
* values.
* @param name the name
* @param p the proportional value
* @param i the integral value
* @param d the derivative value
*/
PIDSubsystem::PIDSubsystem(const char *name, double p, double i, double d) :
Subsystem(name)
{
m_controller = new PIDController(p, i, d, this, this);
PIDSubsystem::PIDSubsystem(const char *name, double p, double i, double d)
: Subsystem(name) {
m_controller = new PIDController(p, i, d, this, this);
}
/**
* Instantiates a {@link PIDSubsystem} that will use the given p, i and d values.
* Instantiates a {@link PIDSubsystem} that will use the given p, i and d
* values.
* @param name the name
* @param p the proportional value
* @param i the integral value
* @param d the derivative value
* @param f the feedforward value
*/
PIDSubsystem::PIDSubsystem(const char *name, double p, double i, double d, double f) :
Subsystem(name)
{
m_controller = new PIDController(p, i, d, f, this, this);
PIDSubsystem::PIDSubsystem(const char *name, double p, double i, double d,
double f)
: Subsystem(name) {
m_controller = new PIDController(p, i, d, f, this, this);
}
/**
* Instantiates a {@link PIDSubsystem} that will use the given p, i and d values. It will also space the time
* Instantiates a {@link PIDSubsystem} that will use the given p, i and d
* values. It will also space the time
* between PID loop calculations to be equal to the given period.
* @param name the name
* @param p the proportional value
@@ -45,42 +48,42 @@ PIDSubsystem::PIDSubsystem(const char *name, double p, double i, double d, doubl
* @param f the feedfoward value
* @param period the time (in seconds) between calculations
*/
PIDSubsystem::PIDSubsystem(const char *name, double p, double i, double d, double f,
double period) :
Subsystem(name)
{
m_controller = new PIDController(p, i, d, f, this, this, period);
PIDSubsystem::PIDSubsystem(const char *name, double p, double i, double d,
double f, double period)
: Subsystem(name) {
m_controller = new PIDController(p, i, d, f, this, this, period);
}
/**
* Instantiates a {@link PIDSubsystem} that will use the given p, i and d values.
* Instantiates a {@link PIDSubsystem} that will use the given p, i and d
* values.
* It will use the class name as its name.
* @param p the proportional value
* @param i the integral value
* @param d the derivative value
*/
PIDSubsystem::PIDSubsystem(double p, double i, double d) :
Subsystem("PIDSubsystem")
{
m_controller = new PIDController(p, i, d, this, this);
PIDSubsystem::PIDSubsystem(double p, double i, double d)
: Subsystem("PIDSubsystem") {
m_controller = new PIDController(p, i, d, this, this);
}
/**
* Instantiates a {@link PIDSubsystem} that will use the given p, i and d values.
* Instantiates a {@link PIDSubsystem} that will use the given p, i and d
* values.
* It will use the class name as its name.
* @param p the proportional value
* @param i the integral value
* @param d the derivative value
* @param f the feedforward value
*/
PIDSubsystem::PIDSubsystem(double p, double i, double d, double f) :
Subsystem("PIDSubsystem")
{
m_controller = new PIDController(p, i, d, f, this, this);
PIDSubsystem::PIDSubsystem(double p, double i, double d, double f)
: Subsystem("PIDSubsystem") {
m_controller = new PIDController(p, i, d, f, this, this);
}
/**
* Instantiates a {@link PIDSubsystem} that will use the given p, i and d values.
* Instantiates a {@link PIDSubsystem} that will use the given p, i and d
* values.
* It will use the class name as its name.
* It will also space the time
* between PID loop calculations to be equal to the given period.
@@ -90,33 +93,23 @@ PIDSubsystem::PIDSubsystem(double p, double i, double d, double f) :
* @param f the feedforward value
* @param period the time (in seconds) between calculations
*/
PIDSubsystem::PIDSubsystem(double p, double i, double d, double f, double period) :
Subsystem("PIDSubsystem")
{
m_controller = new PIDController(p, i, d, f, this, this, period);
PIDSubsystem::PIDSubsystem(double p, double i, double d, double f,
double period)
: Subsystem("PIDSubsystem") {
m_controller = new PIDController(p, i, d, f, this, this, period);
}
PIDSubsystem::~PIDSubsystem()
{
delete m_controller;
}
PIDSubsystem::~PIDSubsystem() { delete m_controller; }
/**
* Enables the internal {@link PIDController}
*/
void PIDSubsystem::Enable()
{
m_controller->Enable();
}
void PIDSubsystem::Enable() { m_controller->Enable(); }
/**
* Disables the internal {@link PIDController}
*/
void PIDSubsystem::Disable()
{
m_controller->Disable();
}
void PIDSubsystem::Disable() { m_controller->Disable(); }
/**
* Returns the {@link PIDController} used by this {@link PIDSubsystem}.
@@ -124,21 +117,18 @@ void PIDSubsystem::Disable()
*
* @return the {@link PIDController} used by this {@link PIDSubsystem}
*/
PIDController *PIDSubsystem::GetPIDController()
{
return m_controller;
}
PIDController *PIDSubsystem::GetPIDController() { return m_controller; }
/**
* Sets the setpoint to the given value. If {@link PIDCommand#SetRange(double, double) SetRange(...)}
* Sets the setpoint to the given value. If {@link PIDCommand#SetRange(double,
* double) SetRange(...)}
* was called,
* then the given setpoint
* will be trimmed to fit within the range.
* @param setpoint the new setpoint
*/
void PIDSubsystem::SetSetpoint(double setpoint)
{
m_controller->SetSetpoint(setpoint);
void PIDSubsystem::SetSetpoint(double setpoint) {
m_controller->SetSetpoint(setpoint);
}
/**
@@ -147,19 +137,15 @@ void PIDSubsystem::SetSetpoint(double setpoint)
* then the bounds will still be honored by this method.
* @param deltaSetpoint the change in the setpoint
*/
void PIDSubsystem::SetSetpointRelative(double deltaSetpoint)
{
SetSetpoint(GetSetpoint() + deltaSetpoint);
void PIDSubsystem::SetSetpointRelative(double deltaSetpoint) {
SetSetpoint(GetSetpoint() + deltaSetpoint);
}
/**
* Return the current setpoint
* @return The current setpoint
*/
double PIDSubsystem::GetSetpoint()
{
return m_controller->GetSetpoint();
}
double PIDSubsystem::GetSetpoint() { return m_controller->GetSetpoint(); }
/**
* Sets the maximum and minimum values expected from the input.
@@ -167,9 +153,8 @@ double PIDSubsystem::GetSetpoint()
* @param minimumInput the minimum value expected from the input
* @param maximumInput the maximum value expected from the output
*/
void PIDSubsystem::SetInputRange(float minimumInput, float maximumInput)
{
m_controller->SetInputRange(minimumInput, maximumInput);
void PIDSubsystem::SetInputRange(float minimumInput, float maximumInput) {
m_controller->SetInputRange(minimumInput, maximumInput);
}
/**
@@ -178,9 +163,8 @@ void PIDSubsystem::SetInputRange(float minimumInput, float maximumInput)
* @param minimumOutput the minimum value to write to the output
* @param maximumOutput the maximum value to write to the output
*/
void PIDSubsystem::SetOutputRange(float minimumOutput, float maximumOutput)
{
m_controller->SetOutputRange(minimumOutput, maximumOutput);
void PIDSubsystem::SetOutputRange(float minimumOutput, float maximumOutput) {
m_controller->SetOutputRange(minimumOutput, maximumOutput);
}
/*
@@ -189,7 +173,7 @@ void PIDSubsystem::SetOutputRange(float minimumOutput, float maximumOutput)
* @param percentage error which is tolerable
*/
void PIDSubsystem::SetAbsoluteTolerance(float absValue) {
m_controller->SetAbsoluteTolerance(absValue);
m_controller->SetAbsoluteTolerance(absValue);
}
/*
@@ -198,49 +182,38 @@ void PIDSubsystem::SetAbsoluteTolerance(float absValue) {
* @param percentage error which is tolerable
*/
void PIDSubsystem::SetPercentTolerance(float percent) {
m_controller->SetPercentTolerance(percent);
m_controller->SetPercentTolerance(percent);
}
/*
* Return true if the error is within the percentage of the total input range,
* determined by SetTolerance. This asssumes that the maximum and minimum input
* were set using SetInput. Use OnTarget() in the IsFinished() method of commands
* were set using SetInput. Use OnTarget() in the IsFinished() method of
* commands
* that use this subsystem.
*
* Currently this just reports on target as the actual value passes through the setpoint.
* Ideally it should be based on being within the tolerance for some period of time.
* Currently this just reports on target as the actual value passes through the
* setpoint.
* Ideally it should be based on being within the tolerance for some period of
* time.
*
* @return true if the error is within the percentage tolerance of the input range
* @return true if the error is within the percentage tolerance of the input
* range
*/
bool PIDSubsystem::OnTarget() const
{
return m_controller->OnTarget();
}
bool PIDSubsystem::OnTarget() const { return m_controller->OnTarget(); }
/**
* Returns the current position
* @return the current position
*/
double PIDSubsystem::GetPosition()
{
return ReturnPIDInput();
}
double PIDSubsystem::GetPosition() { return ReturnPIDInput(); }
void PIDSubsystem::PIDWrite(float output)
{
UsePIDOutput(output);
}
void PIDSubsystem::PIDWrite(float output) { UsePIDOutput(output); }
double PIDSubsystem::PIDGet() const
{
return ReturnPIDInput();
}
double PIDSubsystem::PIDGet() const { return ReturnPIDInput(); }
std::string PIDSubsystem::GetSmartDashboardType() const {
return "PIDCommand";
}
void PIDSubsystem::InitTable(ITable* table){
m_controller->InitTable(table);
Subsystem::InitTable(table);
std::string PIDSubsystem::GetSmartDashboardType() const { return "PIDCommand"; }
void PIDSubsystem::InitTable(ITable *table) {
m_controller->InitTable(table);
Subsystem::InitTable(table);
}

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -8,30 +9,20 @@
#include "stdio.h"
#include <sstream>
PrintCommand::PrintCommand(const char *message) :
Command(((std::stringstream&)(std::stringstream("Print \"") << message << "\"")).str().c_str())
{
m_message = message;
PrintCommand::PrintCommand(const char *message)
: Command(((std::stringstream &)(std::stringstream("Print \"") << message
<< "\""))
.str()
.c_str()) {
m_message = message;
}
void PrintCommand::Initialize()
{
printf("%s", m_message.c_str());
}
void PrintCommand::Initialize() { printf("%s", m_message.c_str()); }
void PrintCommand::Execute()
{
}
void PrintCommand::Execute() {}
bool PrintCommand::IsFinished()
{
return true;
}
bool PrintCommand::IsFinished() { return true; }
void PrintCommand::End()
{
}
void PrintCommand::End() {}
void PrintCommand::Interrupted()
{
}
void PrintCommand::Interrupted() {}

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -17,27 +18,27 @@
Scheduler *Scheduler::_instance = NULL;
Scheduler::Scheduler() :
m_buttonsLock(NULL), m_additionsLock(NULL), m_adding(false) {
m_buttonsLock = initializeMutexNormal();
m_additionsLock = initializeMutexNormal();
Scheduler::Scheduler()
: m_buttonsLock(NULL), m_additionsLock(NULL), m_adding(false) {
m_buttonsLock = initializeMutexNormal();
m_additionsLock = initializeMutexNormal();
HLUsageReporting::ReportScheduler();
HLUsageReporting::ReportScheduler();
m_table = NULL;
m_enabled = true;
m_runningCommandsChanged = false;
toCancel = NULL;
commands = NULL;
ids = NULL;
m_table = NULL;
m_enabled = true;
m_runningCommandsChanged = false;
toCancel = NULL;
commands = NULL;
ids = NULL;
}
Scheduler::~Scheduler() {
takeMutex(m_additionsLock);
deleteMutex(m_additionsLock);
takeMutex(m_additionsLock);
deleteMutex(m_additionsLock);
takeMutex(m_buttonsLock);
deleteMutex(m_buttonsLock);
takeMutex(m_buttonsLock);
deleteMutex(m_buttonsLock);
}
/**
@@ -45,78 +46,77 @@ Scheduler::~Scheduler() {
* @return the {@link Scheduler}
*/
Scheduler *Scheduler::GetInstance() {
if (_instance == NULL)
_instance = new Scheduler();
return _instance;
if (_instance == NULL) _instance = new Scheduler();
return _instance;
}
void Scheduler::SetEnabled(bool enabled) {
m_enabled = enabled;
}
void Scheduler::SetEnabled(bool enabled) { m_enabled = enabled; }
/**
* Add a command to be scheduled later.
* In any pass through the scheduler, all commands are added to the additions list, then
* In any pass through the scheduler, all commands are added to the additions
* list, then
* at the end of the pass, they are all scheduled.
* @param command The command to be scheduled
*/
void Scheduler::AddCommand(Command *command) {
Synchronized sync(m_additionsLock);
if (std::find(m_additions.begin(), m_additions.end(), command)
!= m_additions.end())
return;
m_additions.push_back(command);
Synchronized sync(m_additionsLock);
if (std::find(m_additions.begin(), m_additions.end(), command) !=
m_additions.end())
return;
m_additions.push_back(command);
}
void Scheduler::AddButton(ButtonScheduler *button) {
Synchronized sync(m_buttonsLock);
m_buttons.push_back(button);
Synchronized sync(m_buttonsLock);
m_buttons.push_back(button);
}
void Scheduler::ProcessCommandAddition(Command *command) {
if (command == NULL)
return;
if (command == NULL) return;
// Check to make sure no adding during adding
if (m_adding) {
wpi_setWPIErrorWithContext(IncompatibleState, "Can not start command from cancel method");
return;
}
// Check to make sure no adding during adding
if (m_adding) {
wpi_setWPIErrorWithContext(IncompatibleState,
"Can not start command from cancel method");
return;
}
// Only add if not already in
CommandSet::iterator found = m_commands.find(command);
if (found == m_commands.end()) {
// Check that the requirements can be had
Command::SubsystemSet requirements = command->GetRequirements();
Command::SubsystemSet::iterator iter;
for (iter = requirements.begin(); iter != requirements.end(); iter++) {
Subsystem *lock = *iter;
if (lock->GetCurrentCommand() != NULL
&& !lock->GetCurrentCommand()->IsInterruptible())
return;
}
// Only add if not already in
CommandSet::iterator found = m_commands.find(command);
if (found == m_commands.end()) {
// Check that the requirements can be had
Command::SubsystemSet requirements = command->GetRequirements();
Command::SubsystemSet::iterator iter;
for (iter = requirements.begin(); iter != requirements.end(); iter++) {
Subsystem *lock = *iter;
if (lock->GetCurrentCommand() != NULL &&
!lock->GetCurrentCommand()->IsInterruptible())
return;
}
// Give it the requirements
m_adding = true;
for (iter = requirements.begin(); iter != requirements.end(); iter++) {
Subsystem *lock = *iter;
if (lock->GetCurrentCommand() != NULL) {
lock->GetCurrentCommand()->Cancel();
Remove(lock->GetCurrentCommand());
}
lock->SetCurrentCommand(command);
}
m_adding = false;
// Give it the requirements
m_adding = true;
for (iter = requirements.begin(); iter != requirements.end(); iter++) {
Subsystem *lock = *iter;
if (lock->GetCurrentCommand() != NULL) {
lock->GetCurrentCommand()->Cancel();
Remove(lock->GetCurrentCommand());
}
lock->SetCurrentCommand(command);
}
m_adding = false;
m_commands.insert(command);
m_commands.insert(command);
command->StartRunning();
m_runningCommandsChanged = true;
}
command->StartRunning();
m_runningCommandsChanged = true;
}
}
/**
* Runs a single iteration of the loop. This method should be called often in order to have a functioning
* Runs a single iteration of the loop. This method should be called often in
* order to have a functioning
* {@link Command} system. The loop has five stages:
*
* <ol>
@@ -128,66 +128,67 @@ void Scheduler::ProcessCommandAddition(Command *command) {
* </ol>
*/
void Scheduler::Run() {
// Get button input (going backwards preserves button priority)
{
if (!m_enabled)
return;
// Get button input (going backwards preserves button priority)
{
if (!m_enabled) return;
Synchronized sync(m_buttonsLock);
ButtonVector::reverse_iterator rButtonIter = m_buttons.rbegin();
for (; rButtonIter != m_buttons.rend(); rButtonIter++) {
(*rButtonIter)->Execute();
}
}
m_runningCommandsChanged = false;
Synchronized sync(m_buttonsLock);
ButtonVector::reverse_iterator rButtonIter = m_buttons.rbegin();
for (; rButtonIter != m_buttons.rend(); rButtonIter++) {
(*rButtonIter)->Execute();
}
}
// Loop through the commands
CommandSet::iterator commandIter = m_commands.begin();
for (; commandIter != m_commands.end();) {
Command *command = *commandIter;
// Increment before potentially removing to keep the iterator valid
commandIter++;
if (!command->Run()) {
Remove(command);
m_runningCommandsChanged = true;
}
}
m_runningCommandsChanged = false;
// Add the new things
{
Synchronized sync(m_additionsLock);
CommandVector::iterator additionsIter = m_additions.begin();
for (; additionsIter != m_additions.end(); additionsIter++) {
ProcessCommandAddition(*additionsIter);
}
m_additions.clear();
}
// Loop through the commands
CommandSet::iterator commandIter = m_commands.begin();
for (; commandIter != m_commands.end();) {
Command *command = *commandIter;
// Increment before potentially removing to keep the iterator valid
commandIter++;
if (!command->Run()) {
Remove(command);
m_runningCommandsChanged = true;
}
}
// Add in the defaults
Command::SubsystemSet::iterator subsystemIter = m_subsystems.begin();
for (; subsystemIter != m_subsystems.end(); subsystemIter++) {
Subsystem *lock = *subsystemIter;
if (lock->GetCurrentCommand() == NULL) {
ProcessCommandAddition(lock->GetDefaultCommand());
}
lock->ConfirmCommand();
}
// Add the new things
{
Synchronized sync(m_additionsLock);
CommandVector::iterator additionsIter = m_additions.begin();
for (; additionsIter != m_additions.end(); additionsIter++) {
ProcessCommandAddition(*additionsIter);
}
m_additions.clear();
}
UpdateTable();
// Add in the defaults
Command::SubsystemSet::iterator subsystemIter = m_subsystems.begin();
for (; subsystemIter != m_subsystems.end(); subsystemIter++) {
Subsystem *lock = *subsystemIter;
if (lock->GetCurrentCommand() == NULL) {
ProcessCommandAddition(lock->GetDefaultCommand());
}
lock->ConfirmCommand();
}
UpdateTable();
}
/**
* Registers a {@link Subsystem} to this {@link Scheduler}, so that the {@link Scheduler} might know
* if a default {@link Command} needs to be run. All {@link Subsystem Subsystems} should call this.
* Registers a {@link Subsystem} to this {@link Scheduler}, so that the {@link
* Scheduler} might know
* if a default {@link Command} needs to be run. All {@link Subsystem
* Subsystems} should call this.
* @param system the system
*/
void Scheduler::RegisterSubsystem(Subsystem *subsystem) {
if (subsystem == NULL) {
wpi_setWPIErrorWithContext(NullParameter, "subsystem");
return;
}
m_subsystems.insert(subsystem);
if (subsystem == NULL) {
wpi_setWPIErrorWithContext(NullParameter, "subsystem");
return;
}
m_subsystems.insert(subsystem);
}
/**
@@ -195,107 +196,99 @@ void Scheduler::RegisterSubsystem(Subsystem *subsystem) {
* @param command the command to remove
*/
void Scheduler::Remove(Command *command) {
if (command == NULL) {
wpi_setWPIErrorWithContext(NullParameter, "command");
return;
}
if (command == NULL) {
wpi_setWPIErrorWithContext(NullParameter, "command");
return;
}
if (!m_commands.erase(command))
return;
if (!m_commands.erase(command)) return;
Command::SubsystemSet requirements = command->GetRequirements();
Command::SubsystemSet::iterator iter = requirements.begin();
for (; iter != requirements.end(); iter++) {
Subsystem *lock = *iter;
lock->SetCurrentCommand(NULL);
}
Command::SubsystemSet requirements = command->GetRequirements();
Command::SubsystemSet::iterator iter = requirements.begin();
for (; iter != requirements.end(); iter++) {
Subsystem *lock = *iter;
lock->SetCurrentCommand(NULL);
}
command->Removed();
command->Removed();
}
void Scheduler::RemoveAll() {
while (m_commands.size() > 0) {
Remove(*m_commands.begin());
}
while (m_commands.size() > 0) {
Remove(*m_commands.begin());
}
}
/**
* Completely resets the scheduler. Undefined behavior if running.
*/
void Scheduler::ResetAll()
{
RemoveAll();
m_subsystems.clear();
m_buttons.clear();
m_additions.clear();
m_commands.clear();
m_table = NULL;
void Scheduler::ResetAll() {
RemoveAll();
m_subsystems.clear();
m_buttons.clear();
m_additions.clear();
m_commands.clear();
m_table = NULL;
}
/**
* Update the network tables associated with the Scheduler object on the SmartDashboard
* Update the network tables associated with the Scheduler object on the
* SmartDashboard
*/
void Scheduler::UpdateTable() {
CommandSet::iterator commandIter;
if (m_table != NULL) {
// Get the list of possible commands to cancel
m_table->RetrieveValue("Cancel", *toCancel);
// m_table->RetrieveValue("Ids", *ids);
CommandSet::iterator commandIter;
if (m_table != NULL) {
// Get the list of possible commands to cancel
m_table->RetrieveValue("Cancel", *toCancel);
// m_table->RetrieveValue("Ids", *ids);
// cancel commands that have had the cancel buttons pressed
// on the SmartDashboad
if (toCancel->size() > 0) {
for (commandIter = m_commands.begin(); commandIter
!= m_commands.end(); ++commandIter) {
for (unsigned i = 0; i < toCancel->size(); i++) {
Command *c = *commandIter;
if (c->GetID() == toCancel->get(i)) {
c->Cancel();
}
}
}
toCancel->setSize(0);
m_table->PutValue("Cancel", *toCancel);
}
// Set the running commands
if (m_runningCommandsChanged) {
commands->setSize(0);
ids->setSize(0);
for (commandIter = m_commands.begin(); commandIter != m_commands.end(); ++commandIter) {
Command *c = *commandIter;
commands->add(c->GetName());
ids->add(c->GetID());
}
m_table->PutValue("Names", *commands);
m_table->PutValue("Ids", *ids);
}
}
// cancel commands that have had the cancel buttons pressed
// on the SmartDashboad
if (toCancel->size() > 0) {
for (commandIter = m_commands.begin(); commandIter != m_commands.end();
++commandIter) {
for (unsigned i = 0; i < toCancel->size(); i++) {
Command *c = *commandIter;
if (c->GetID() == toCancel->get(i)) {
c->Cancel();
}
}
}
toCancel->setSize(0);
m_table->PutValue("Cancel", *toCancel);
}
// Set the running commands
if (m_runningCommandsChanged) {
commands->setSize(0);
ids->setSize(0);
for (commandIter = m_commands.begin(); commandIter != m_commands.end();
++commandIter) {
Command *c = *commandIter;
commands->add(c->GetName());
ids->add(c->GetID());
}
m_table->PutValue("Names", *commands);
m_table->PutValue("Ids", *ids);
}
}
}
std::string Scheduler::GetName() {
return "Scheduler";
}
std::string Scheduler::GetName() { return "Scheduler"; }
std::string Scheduler::GetType() const {
return "Scheduler";
}
std::string Scheduler::GetType() const { return "Scheduler"; }
std::string Scheduler::GetSmartDashboardType() const {
return "Scheduler";
}
std::string Scheduler::GetSmartDashboardType() const { return "Scheduler"; }
void Scheduler::InitTable(ITable *subTable) {
m_table = subTable;
commands = new StringArray();
ids = new NumberArray();
toCancel = new NumberArray();
m_table = subTable;
commands = new StringArray();
ids = new NumberArray();
toCancel = new NumberArray();
m_table->PutValue("Names", *commands);
m_table->PutValue("Ids", *ids);
m_table->PutValue("Cancel", *toCancel);
m_table->PutValue("Names", *commands);
m_table->PutValue("Ids", *ids);
m_table->PutValue("Cancel", *toCancel);
}
ITable * Scheduler::GetTable() const {
return m_table;
}
ITable *Scheduler::GetTable() const { return m_table; }

View File

@@ -1,35 +1,22 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
#include "Commands/StartCommand.h"
StartCommand::StartCommand(Command *commandToStart) :
Command("StartCommand")
{
m_commandToFork = commandToStart;
StartCommand::StartCommand(Command *commandToStart) : Command("StartCommand") {
m_commandToFork = commandToStart;
}
void StartCommand::Initialize()
{
m_commandToFork->Start();
}
void StartCommand::Initialize() { m_commandToFork->Start(); }
void StartCommand::Execute()
{
}
void StartCommand::Execute() {}
void StartCommand::End()
{
}
void StartCommand::End() {}
void StartCommand::Interrupted()
{
}
void StartCommand::Interrupted() {}
bool StartCommand::IsFinished()
{
return true;
}
bool StartCommand::IsFinished() { return true; }

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -14,166 +15,138 @@
* Creates a subsystem with the given name
* @param name the name of the subsystem
*/
Subsystem::Subsystem(const char *name) :
m_currentCommand(NULL),
m_defaultCommand(NULL),
m_initializedDefaultCommand(false)
{
m_name = name;
Scheduler::GetInstance()->RegisterSubsystem(this);
m_table = NULL;
m_currentCommandChanged = true;
Subsystem::Subsystem(const char *name)
: m_currentCommand(NULL),
m_defaultCommand(NULL),
m_initializedDefaultCommand(false) {
m_name = name;
Scheduler::GetInstance()->RegisterSubsystem(this);
m_table = NULL;
m_currentCommandChanged = true;
}
/**
* Initialize the default command for this subsystem
* This is meant to be the place to call SetDefaultCommand in a subsystem and will be called
* on all the subsystems by the CommandBase method before the program starts running by using
* This is meant to be the place to call SetDefaultCommand in a subsystem and
* will be called
* on all the subsystems by the CommandBase method before the program starts
* running by using
* the list of all registered Subsystems inside the Scheduler.
*
*
* This should be overridden by a Subsystem that has a default Command
*/
void Subsystem::InitDefaultCommand() {
}
void Subsystem::InitDefaultCommand() {}
/**
* Sets the default command. If this is not called or is called with null,
* then there will be no default command for the subsystem.
*
* <p><b>WARNING:</b> This should <b>NOT</b> be called in a constructor if the subsystem is a
* <p><b>WARNING:</b> This should <b>NOT</b> be called in a constructor if the
* subsystem is a
* singleton.</p>
*
* @param command the default command (or null if there should be none)
*/
void Subsystem::SetDefaultCommand(Command *command)
{
if (command == NULL)
{
m_defaultCommand = NULL;
}
else
{
bool found = false;
Command::SubsystemSet requirements = command->GetRequirements();
Command::SubsystemSet::iterator iter = requirements.begin();
for (; iter != requirements.end(); iter++)
{
if (*iter == this)
{
found = true;
break;
}
}
void Subsystem::SetDefaultCommand(Command *command) {
if (command == NULL) {
m_defaultCommand = NULL;
} else {
bool found = false;
Command::SubsystemSet requirements = command->GetRequirements();
Command::SubsystemSet::iterator iter = requirements.begin();
for (; iter != requirements.end(); iter++) {
if (*iter == this) {
found = true;
break;
}
}
if (!found)
{
wpi_setWPIErrorWithContext(CommandIllegalUse, "A default command must require the subsystem");
return;
}
m_defaultCommand = command;
}
if (m_table != NULL)
{
if (m_defaultCommand != NULL)
{
m_table->PutBoolean("hasDefault", true);
m_table->PutString("default", m_defaultCommand->GetName());
}
else
{
m_table->PutBoolean("hasDefault", false);
}
}
if (!found) {
wpi_setWPIErrorWithContext(
CommandIllegalUse, "A default command must require the subsystem");
return;
}
m_defaultCommand = command;
}
if (m_table != NULL) {
if (m_defaultCommand != NULL) {
m_table->PutBoolean("hasDefault", true);
m_table->PutString("default", m_defaultCommand->GetName());
} else {
m_table->PutBoolean("hasDefault", false);
}
}
}
/**
* Returns the default command (or null if there is none).
* @return the default command
*/
Command *Subsystem::GetDefaultCommand()
{
if (!m_initializedDefaultCommand) {
m_initializedDefaultCommand = true;
InitDefaultCommand();
}
return m_defaultCommand;
Command *Subsystem::GetDefaultCommand() {
if (!m_initializedDefaultCommand) {
m_initializedDefaultCommand = true;
InitDefaultCommand();
}
return m_defaultCommand;
}
/**
* Sets the current command
* @param command the new current command
*/
void Subsystem::SetCurrentCommand(Command *command)
{
m_currentCommand = command;
m_currentCommandChanged = true;
void Subsystem::SetCurrentCommand(Command *command) {
m_currentCommand = command;
m_currentCommandChanged = true;
}
/**
* Returns the command which currently claims this subsystem.
* @return the command which currently claims this subsystem
*/
Command *Subsystem::GetCurrentCommand() const
{
return m_currentCommand;
}
Command *Subsystem::GetCurrentCommand() const { return m_currentCommand; }
/**
* Call this to alert Subsystem that the current command is actually the command.
* Sometimes, the {@link Subsystem} is told that it has no command while the {@link Scheduler}
* is going through the loop, only to be soon after given a new one. This will avoid that situation.
* Call this to alert Subsystem that the current command is actually the
* command.
* Sometimes, the {@link Subsystem} is told that it has no command while the
* {@link Scheduler}
* is going through the loop, only to be soon after given a new one. This will
* avoid that situation.
*/
void Subsystem::ConfirmCommand()
{
if (m_currentCommandChanged) {
if (m_table != NULL)
{
if (m_currentCommand != NULL)
{
m_table->PutBoolean("hasCommand", true);
m_table->PutString("command", m_currentCommand->GetName());
}
else
{
m_table->PutBoolean("hasCommand", false);
}
}
m_currentCommandChanged = false;
}
}
std::string Subsystem::GetName()
{
return m_name;
}
std::string Subsystem::GetSmartDashboardType() const
{
return "Subsystem";
}
void Subsystem::InitTable(ITable* table)
{
m_table = table;
if(m_table!=NULL){
if (m_defaultCommand != NULL) {
m_table->PutBoolean("hasDefault", true);
m_table->PutString("default", m_defaultCommand->GetName());
} else {
m_table->PutBoolean("hasDefault", false);
}
if (m_currentCommand != NULL) {
m_table->PutBoolean("hasCommand", true);
m_table->PutString("command", m_currentCommand->GetName());
} else {
m_table->PutBoolean("hasCommand", false);
}
void Subsystem::ConfirmCommand() {
if (m_currentCommandChanged) {
if (m_table != NULL) {
if (m_currentCommand != NULL) {
m_table->PutBoolean("hasCommand", true);
m_table->PutString("command", m_currentCommand->GetName());
} else {
m_table->PutBoolean("hasCommand", false);
}
}
m_currentCommandChanged = false;
}
}
ITable* Subsystem::GetTable() const {
return m_table;
std::string Subsystem::GetName() { return m_name; }
std::string Subsystem::GetSmartDashboardType() const { return "Subsystem"; }
void Subsystem::InitTable(ITable *table) {
m_table = table;
if (m_table != NULL) {
if (m_defaultCommand != NULL) {
m_table->PutBoolean("hasDefault", true);
m_table->PutString("default", m_defaultCommand->GetName());
} else {
m_table->PutBoolean("hasDefault", false);
}
if (m_currentCommand != NULL) {
m_table->PutBoolean("hasCommand", true);
m_table->PutString("command", m_currentCommand->GetName());
} else {
m_table->PutBoolean("hasCommand", false);
}
}
}
ITable *Subsystem::GetTable() const { return m_table; }

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -7,33 +8,22 @@
#include "Commands/WaitCommand.h"
#include <sstream>
WaitCommand::WaitCommand(double timeout) :
Command(((std::stringstream&)(std::stringstream("Wait(") << timeout << ")")).str().c_str(), timeout)
{
}
WaitCommand::WaitCommand(double timeout)
: Command(
((std::stringstream &)(std::stringstream("Wait(") << timeout << ")"))
.str()
.c_str(),
timeout) {}
WaitCommand::WaitCommand(const char *name, double timeout) :
Command(name, timeout)
{
}
WaitCommand::WaitCommand(const char *name, double timeout)
: Command(name, timeout) {}
void WaitCommand::Initialize()
{
}
void WaitCommand::Initialize() {}
void WaitCommand::Execute()
{
}
void WaitCommand::Execute() {}
bool WaitCommand::IsFinished()
{
return IsTimedOut();
}
bool WaitCommand::IsFinished() { return IsTimedOut(); }
void WaitCommand::End()
{
}
void WaitCommand::End() {}
void WaitCommand::Interrupted()
{
}
void WaitCommand::Interrupted() {}

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -7,33 +8,20 @@
#include "Commands/WaitForChildren.h"
#include "Commands/CommandGroup.h"
WaitForChildren::WaitForChildren(double timeout) :
Command("WaitForChildren", timeout)
{
}
WaitForChildren::WaitForChildren(double timeout)
: Command("WaitForChildren", timeout) {}
WaitForChildren::WaitForChildren(const char *name, double timeout) :
Command(name, timeout)
{
}
WaitForChildren::WaitForChildren(const char *name, double timeout)
: Command(name, timeout) {}
void WaitForChildren::Initialize()
{
}
void WaitForChildren::Initialize() {}
void WaitForChildren::Execute()
{
}
void WaitForChildren::Execute() {}
void WaitForChildren::End()
{
}
void WaitForChildren::End() {}
void WaitForChildren::Interrupted()
{
}
void WaitForChildren::Interrupted() {}
bool WaitForChildren::IsFinished()
{
return GetGroup() == NULL || GetGroup()->GetSize() == 0;
bool WaitForChildren::IsFinished() {
return GetGroup() == NULL || GetGroup()->GetSize() == 0;
}

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -13,38 +14,25 @@
* next command.
* @see CommandGroup
*/
WaitUntilCommand::WaitUntilCommand(double time) :
Command("WaitUntilCommand", time)
{
m_time = time;
WaitUntilCommand::WaitUntilCommand(double time)
: Command("WaitUntilCommand", time) {
m_time = time;
}
WaitUntilCommand::WaitUntilCommand(const char *name, double time) :
Command(name, time)
{
m_time = time;
WaitUntilCommand::WaitUntilCommand(const char *name, double time)
: Command(name, time) {
m_time = time;
}
void WaitUntilCommand::Initialize()
{
}
void WaitUntilCommand::Initialize() {}
void WaitUntilCommand::Execute()
{
}
void WaitUntilCommand::Execute() {}
/**
* Check if we've reached the actual finish time.
*/
bool WaitUntilCommand::IsFinished()
{
return Timer::GetMatchTime() >= m_time;
}
bool WaitUntilCommand::IsFinished() { return Timer::GetMatchTime() >= m_time; }
void WaitUntilCommand::End()
{
}
void WaitUntilCommand::End() {}
void WaitUntilCommand::Interrupted()
{
}
void WaitUntilCommand::Interrupted() {}

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Copyright (c) FIRST 2008. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -19,93 +20,79 @@
bool Error::m_suspendOnErrorEnabled = false;
Error::Error()
: m_code(0)
, m_lineNumber(0)
, m_originatingObject(NULL)
, m_timestamp (0.0)
{}
: m_code(0), m_lineNumber(0), m_originatingObject(NULL), m_timestamp(0.0) {}
Error::~Error()
{}
Error::~Error() {}
void Error::Clone(Error &error)
{
m_code = error.m_code;
m_message = error.m_message;
m_filename = error.m_filename;
m_function = error.m_function;
m_lineNumber = error.m_lineNumber;
m_originatingObject = error.m_originatingObject;
m_timestamp = error.m_timestamp;
void Error::Clone(Error& error) {
m_code = error.m_code;
m_message = error.m_message;
m_filename = error.m_filename;
m_function = error.m_function;
m_lineNumber = error.m_lineNumber;
m_originatingObject = error.m_originatingObject;
m_timestamp = error.m_timestamp;
}
Error::Code Error::GetCode() const
{ return m_code; }
Error::Code Error::GetCode() const { return m_code; }
const char * Error::GetMessage() const
{ return m_message.c_str(); }
const char* Error::GetMessage() const { return m_message.c_str(); }
const char * Error::GetFilename() const
{ return m_filename.c_str(); }
const char* Error::GetFilename() const { return m_filename.c_str(); }
const char * Error::GetFunction() const
{ return m_function.c_str(); }
const char* Error::GetFunction() const { return m_function.c_str(); }
uint32_t Error::GetLineNumber() const
{ return m_lineNumber; }
uint32_t Error::GetLineNumber() const { return m_lineNumber; }
const ErrorBase* Error::GetOriginatingObject() const
{ return m_originatingObject; }
double Error::GetTimestamp() const
{ return m_timestamp; }
void Error::Set(Code code, const char* contextMessage, const char* filename, const char* function, uint32_t lineNumber, const ErrorBase* originatingObject)
{
bool report = true;
if(code == m_code && GetTime() - m_timestamp < 1)
{
report = false;
}
m_code = code;
m_message = contextMessage;
m_filename = filename;
m_function = function;
m_lineNumber = lineNumber;
m_originatingObject = originatingObject;
if(report)
{
m_timestamp = GetTime();
Report();
}
if (m_suspendOnErrorEnabled) suspendTask(0);
const ErrorBase* Error::GetOriginatingObject() const {
return m_originatingObject;
}
void Error::Report()
{
std::stringstream errorStream;
double Error::GetTimestamp() const { return m_timestamp; }
errorStream << "Error on line " << m_lineNumber << " ";
errorStream << "of "<< basename(m_filename.c_str()) << ": ";
errorStream << m_message << std::endl;
errorStream << GetStackTrace(4);
void Error::Set(Code code, const char* contextMessage, const char* filename,
const char* function, uint32_t lineNumber,
const ErrorBase* originatingObject) {
bool report = true;
std::string error = errorStream.str();
if (code == m_code && GetTime() - m_timestamp < 1) {
report = false;
}
DriverStation::ReportError(error);
m_code = code;
m_message = contextMessage;
m_filename = filename;
m_function = function;
m_lineNumber = lineNumber;
m_originatingObject = originatingObject;
if (report) {
m_timestamp = GetTime();
Report();
}
if (m_suspendOnErrorEnabled) suspendTask(0);
}
void Error::Clear()
{
m_code = 0;
m_message = "";
m_filename = "";
m_function = "";
m_lineNumber = 0;
m_originatingObject = NULL;
m_timestamp = 0.0;
void Error::Report() {
std::stringstream errorStream;
errorStream << "Error on line " << m_lineNumber << " ";
errorStream << "of " << basename(m_filename.c_str()) << ": ";
errorStream << m_message << std::endl;
errorStream << GetStackTrace(4);
std::string error = errorStream.str();
DriverStation::ReportError(error);
}
void Error::Clear() {
m_code = 0;
m_message = "";
m_filename = "";
m_function = "";
m_lineNumber = 0;
m_originatingObject = NULL;
m_timestamp = 0.0;
}

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Copyright (c) FIRST 2008. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -18,68 +19,56 @@ Error ErrorBase::_globalError;
/**
* @brief Initialize the instance status to 0 for now.
*/
ErrorBase::ErrorBase()
{}
ErrorBase::ErrorBase() {}
ErrorBase::~ErrorBase()
{}
ErrorBase::~ErrorBase() {}
/**
* @brief Retrieve the current error.
* Get the current error information associated with this sensor.
*/
Error& ErrorBase::GetError()
{
return m_error;
}
Error& ErrorBase::GetError() { return m_error; }
const Error& ErrorBase::GetError() const
{
return m_error;
}
const Error& ErrorBase::GetError() const { return m_error; }
/**
* @brief Clear the current error information associated with this sensor.
*/
void ErrorBase::ClearError() const
{
m_error.Clear();
}
void ErrorBase::ClearError() const { m_error.Clear(); }
/**
* @brief Set error information associated with a C library call that set an error to the "errno" global variable.
* @brief Set error information associated with a C library call that set an
* error to the "errno" global variable.
*
* @param contextMessage A custom message from the code that set the error.
* @param filename Filename of the error source
* @param function Function of the error source
* @param lineNumber Line number of the error source
*/
void ErrorBase::SetErrnoError(const char *contextMessage,
const char* filename, const char* function, uint32_t lineNumber) const
{
char err[256];
int errNo = errno;
if (errNo == 0)
{
sprintf(err, "OK: %s", contextMessage);
}
else
{
snprintf(err, 256, "%s (0x%08X): %s", strerror(errNo), errNo, contextMessage);
}
void ErrorBase::SetErrnoError(const char* contextMessage, const char* filename,
const char* function, uint32_t lineNumber) const {
char err[256];
int errNo = errno;
if (errNo == 0) {
sprintf(err, "OK: %s", contextMessage);
} else {
snprintf(err, 256, "%s (0x%08X): %s", strerror(errNo), errNo,
contextMessage);
}
// Set the current error information for this object.
m_error.Set(-1, err, filename, function, lineNumber, this);
// Set the current error information for this object.
m_error.Set(-1, err, filename, function, lineNumber, this);
// Update the global error if there is not one already set.
Synchronized mutex(_globalErrorMutex);
if (_globalError.GetCode() == 0) {
_globalError.Clone(m_error);
}
// Update the global error if there is not one already set.
Synchronized mutex(_globalErrorMutex);
if (_globalError.GetCode() == 0) {
_globalError.Clone(m_error);
}
}
/**
* @brief Set the current error information associated from the nivision Imaq API.
* @brief Set the current error information associated from the nivision Imaq
* API.
*
* @param success The return from the function
* @param contextMessage A custom message from the code that set the error.
@@ -87,22 +76,23 @@ void ErrorBase::SetErrnoError(const char *contextMessage,
* @param function Function of the error source
* @param lineNumber Line number of the error source
*/
void ErrorBase::SetImaqError(int success, const char *contextMessage, const char* filename, const char* function, uint32_t lineNumber) const
{
// If there was an error
if (success <= 0) {
char err[256];
sprintf(err, "%i: %s", success, contextMessage);
void ErrorBase::SetImaqError(int success, const char* contextMessage,
const char* filename, const char* function,
uint32_t lineNumber) const {
// If there was an error
if (success <= 0) {
char err[256];
sprintf(err, "%i: %s", success, contextMessage);
// Set the current error information for this object.
m_error.Set(success, err, filename, function, lineNumber, this);
// Set the current error information for this object.
m_error.Set(success, err, filename, function, lineNumber, this);
// Update the global error if there is not one already set.
Synchronized mutex(_globalErrorMutex);
if (_globalError.GetCode() == 0) {
_globalError.Clone(m_error);
}
}
// Update the global error if there is not one already set.
Synchronized mutex(_globalErrorMutex);
if (_globalError.GetCode() == 0) {
_globalError.Clone(m_error);
}
}
}
/**
@@ -114,20 +104,20 @@ void ErrorBase::SetImaqError(int success, const char *contextMessage, const char
* @param function Function of the error source
* @param lineNumber Line number of the error source
*/
void ErrorBase::SetError(Error::Code code, const char *contextMessage,
const char* filename, const char* function, uint32_t lineNumber) const
{
// If there was an error
if (code != 0) {
// Set the current error information for this object.
m_error.Set(code, contextMessage, filename, function, lineNumber, this);
void ErrorBase::SetError(Error::Code code, const char* contextMessage,
const char* filename, const char* function,
uint32_t lineNumber) const {
// If there was an error
if (code != 0) {
// Set the current error information for this object.
m_error.Set(code, contextMessage, filename, function, lineNumber, this);
// Update the global error if there is not one already set.
Synchronized mutex(_globalErrorMutex);
if (_globalError.GetCode() == 0) {
_globalError.Clone(m_error);
}
}
// Update the global error if there is not one already set.
Synchronized mutex(_globalErrorMutex);
if (_globalError.GetCode() == 0) {
_globalError.Clone(m_error);
}
}
}
/**
@@ -139,25 +129,24 @@ void ErrorBase::SetError(Error::Code code, const char *contextMessage,
* @param function Function of the error source
* @param lineNumber Line number of the error source
*/
void ErrorBase::SetWPIError(const char *errorMessage, Error::Code code , const char *contextMessage,
const char* filename, const char* function, uint32_t lineNumber) const
{
char err[256];
sprintf(err, "%s: %s", errorMessage, contextMessage);
void ErrorBase::SetWPIError(const char* errorMessage, Error::Code code,
const char* contextMessage, const char* filename,
const char* function, uint32_t lineNumber) const {
char err[256];
sprintf(err, "%s: %s", errorMessage, contextMessage);
// Set the current error information for this object.
m_error.Set(code, err, filename, function, lineNumber, this);
// Set the current error information for this object.
m_error.Set(code, err, filename, function, lineNumber, this);
// Update the global error if there is not one already set.
Synchronized mutex(_globalErrorMutex);
if (_globalError.GetCode() == 0) {
_globalError.Clone(m_error);
}
// Update the global error if there is not one already set.
Synchronized mutex(_globalErrorMutex);
if (_globalError.GetCode() == 0) {
_globalError.Clone(m_error);
}
}
void ErrorBase::CloneError(ErrorBase *rhs) const
{
m_error.Clone(rhs->GetError());
void ErrorBase::CloneError(ErrorBase* rhs) const {
m_error.Clone(rhs->GetError());
}
/**
@@ -165,41 +154,39 @@ void ErrorBase::CloneError(ErrorBase *rhs) const
@return true if the current error is fatal.
*/
bool ErrorBase::StatusIsFatal() const
{
return m_error.GetCode() < 0;
bool ErrorBase::StatusIsFatal() const { return m_error.GetCode() < 0; }
void ErrorBase::SetGlobalError(Error::Code code, const char* contextMessage,
const char* filename, const char* function,
uint32_t lineNumber) {
// If there was an error
if (code != 0) {
Synchronized mutex(_globalErrorMutex);
// Set the current error information for this object.
_globalError.Set(code, contextMessage, filename, function, lineNumber,
NULL);
}
}
void ErrorBase::SetGlobalError(Error::Code code, const char *contextMessage,
const char* filename, const char* function, uint32_t lineNumber)
{
// If there was an error
if (code != 0) {
Synchronized mutex(_globalErrorMutex);
void ErrorBase::SetGlobalWPIError(const char* errorMessage,
const char* contextMessage,
const char* filename, const char* function,
uint32_t lineNumber) {
char err[256];
sprintf(err, "%s: %s", errorMessage, contextMessage);
// Set the current error information for this object.
_globalError.Set(code, contextMessage, filename, function, lineNumber, NULL);
}
}
void ErrorBase::SetGlobalWPIError(const char *errorMessage, const char *contextMessage,
const char* filename, const char* function, uint32_t lineNumber)
{
char err[256];
sprintf(err, "%s: %s", errorMessage, contextMessage);
Synchronized mutex(_globalErrorMutex);
if (_globalError.GetCode() != 0) {
_globalError.Clear();
}
_globalError.Set(-1, err, filename, function, lineNumber, NULL);
Synchronized mutex(_globalErrorMutex);
if (_globalError.GetCode() != 0) {
_globalError.Clear();
}
_globalError.Set(-1, err, filename, function, lineNumber, NULL);
}
/**
* Retrieve the current global error.
*/
Error& ErrorBase::GetGlobalError()
{
Synchronized mutex(_globalErrorMutex);
return _globalError;
Error& ErrorBase::GetGlobalError() {
Synchronized mutex(_globalErrorMutex);
return _globalError;
}

View File

@@ -4,17 +4,17 @@
HLUsageReportingInterface* HLUsageReporting::impl = 0;
void HLUsageReporting::SetImplementation(HLUsageReportingInterface* i) {
impl = i;
impl = i;
}
void HLUsageReporting::ReportScheduler() {
if (impl != 0) {
impl->ReportScheduler();
}
if (impl != 0) {
impl->ReportScheduler();
}
}
void HLUsageReporting::ReportSmartDashboard() {
if (impl != 0) {
impl->ReportSmartDashboard();
}
if (impl != 0) {
impl->ReportSmartDashboard();
}
}

View File

@@ -5,138 +5,130 @@
/**
* Get an instance of the LiveWindow main class
* This is a singleton to guarantee that there is only a single instance regardless of
* This is a singleton to guarantee that there is only a single instance
* regardless of
* how many times GetInstance is called.
*/
LiveWindow * LiveWindow::GetInstance()
{
static LiveWindow* instance = new LiveWindow();
LiveWindow *LiveWindow::GetInstance() {
static LiveWindow *instance = new LiveWindow();
return instance;
return instance;
}
/**
* LiveWindow constructor.
* Allocate the necessary tables.
*/
LiveWindow::LiveWindow()
{
m_enabled = false;
m_liveWindowTable = NetworkTable::GetTable("LiveWindow");
m_statusTable = m_liveWindowTable->GetSubTable("~STATUS~");
m_scheduler = Scheduler::GetInstance();
LiveWindow::LiveWindow() {
m_enabled = false;
m_liveWindowTable = NetworkTable::GetTable("LiveWindow");
m_statusTable = m_liveWindowTable->GetSubTable("~STATUS~");
m_scheduler = Scheduler::GetInstance();
}
/**
* Change the enabled status of LiveWindow
* If it changes to enabled, start livewindow running otherwise stop it
*/
void LiveWindow::SetEnabled(bool enabled)
{
if (m_enabled == enabled)
return;
if (enabled)
{
if (m_firstTime)
{
InitializeLiveWindowComponents();
m_firstTime = false;
}
m_scheduler->SetEnabled(false);
m_scheduler->RemoveAll();
for (std::map<LiveWindowSendable *, LiveWindowComponent>::iterator it =
m_components.begin(); it != m_components.end(); ++it)
{
it->first->StartLiveWindowMode();
}
}
else
{
for (std::map<LiveWindowSendable *, LiveWindowComponent>::iterator it =
m_components.begin(); it != m_components.end(); ++it)
{
it->first->StopLiveWindowMode();
}
m_scheduler->SetEnabled(true);
}
m_enabled = enabled;
m_statusTable->PutBoolean("LW Enabled", m_enabled);
void LiveWindow::SetEnabled(bool enabled) {
if (m_enabled == enabled) return;
if (enabled) {
if (m_firstTime) {
InitializeLiveWindowComponents();
m_firstTime = false;
}
m_scheduler->SetEnabled(false);
m_scheduler->RemoveAll();
for (std::map<LiveWindowSendable *, LiveWindowComponent>::iterator it =
m_components.begin();
it != m_components.end(); ++it) {
it->first->StartLiveWindowMode();
}
} else {
for (std::map<LiveWindowSendable *, LiveWindowComponent>::iterator it =
m_components.begin();
it != m_components.end(); ++it) {
it->first->StopLiveWindowMode();
}
m_scheduler->SetEnabled(true);
}
m_enabled = enabled;
m_statusTable->PutBoolean("LW Enabled", m_enabled);
}
LiveWindow::~LiveWindow()
{
}
LiveWindow::~LiveWindow() {}
/**
* Add a Sensor associated with the subsystem and with call it by the given name.
* Add a Sensor associated with the subsystem and with call it by the given
* name.
* @param subsystem The subsystem this component is part of.
* @param name The name of this component.
* @param component A LiveWindowSendable component that represents a sensor.
*/
void LiveWindow::AddSensor(const char *subsystem, const char *name,
LiveWindowSendable *component)
{
m_components[component].subsystem = subsystem;
m_components[component].name = name;
m_components[component].isSensor = true;
LiveWindowSendable *component) {
m_components[component].subsystem = subsystem;
m_components[component].name = name;
m_components[component].isSensor = true;
}
/**
* Add an Actuator associated with the subsystem and with call it by the given name.
* Add an Actuator associated with the subsystem and with call it by the given
* name.
* @param subsystem The subsystem this component is part of.
* @param name The name of this component.
* @param component A LiveWindowSendable component that represents a actuator.
*/
void LiveWindow::AddActuator(const char *subsystem, const char *name,
LiveWindowSendable *component)
{
m_components[component].subsystem = subsystem;
m_components[component].name = name;
m_components[component].isSensor = false;
LiveWindowSendable *component) {
m_components[component].subsystem = subsystem;
m_components[component].name = name;
m_components[component].isSensor = false;
}
/**
* INTERNAL
*/
void LiveWindow::AddSensor(std::string type, int channel, LiveWindowSendable *component)
{
std::ostringstream oss;
oss << type << "[" << channel << "]";
std::string types(oss.str());
char* cc = new char[types.size() + 1];
types.copy(cc, types.size());
cc[types.size()]='\0';
AddSensor("Ungrouped", cc, component);
if (std::find(m_sensors.begin(), m_sensors.end(), component) == m_sensors.end())
m_sensors.push_back(component);
void LiveWindow::AddSensor(std::string type, int channel,
LiveWindowSendable *component) {
std::ostringstream oss;
oss << type << "[" << channel << "]";
std::string types(oss.str());
char *cc = new char[types.size() + 1];
types.copy(cc, types.size());
cc[types.size()] = '\0';
AddSensor("Ungrouped", cc, component);
if (std::find(m_sensors.begin(), m_sensors.end(), component) ==
m_sensors.end())
m_sensors.push_back(component);
}
/**
* INTERNAL
*/
void LiveWindow::AddActuator(std::string type, int channel, LiveWindowSendable *component)
{
std::ostringstream oss;
oss << type << "[" << channel << "]";
std::string types(oss.str());
char* cc = new char[types.size() + 1];
types.copy(cc, types.size());
cc[types.size()]='\0';
AddActuator("Ungrouped", cc, component);
void LiveWindow::AddActuator(std::string type, int channel,
LiveWindowSendable *component) {
std::ostringstream oss;
oss << type << "[" << channel << "]";
std::string types(oss.str());
char *cc = new char[types.size() + 1];
types.copy(cc, types.size());
cc[types.size()] = '\0';
AddActuator("Ungrouped", cc, component);
}
/**
* INTERNAL
*/
void LiveWindow::AddActuator(std::string type, int module, int channel, LiveWindowSendable *component)
{
std::ostringstream oss;
oss << type << "[" << module << "," << channel << "]";
std::string types(oss.str());
char* cc = new char[types.size() + 1];
types.copy(cc, types.size());
cc[types.size()]='\0';
AddActuator("Ungrouped", cc, component);
void LiveWindow::AddActuator(std::string type, int module, int channel,
LiveWindowSendable *component) {
std::ostringstream oss;
oss << type << "[" << module << "," << channel << "]";
std::string types(oss.str());
char *cc = new char[types.size() + 1];
types.copy(cc, types.size());
cc[types.size()] = '\0';
AddActuator("Ungrouped", cc, component);
}
/**
@@ -144,53 +136,51 @@ void LiveWindow::AddActuator(std::string type, int module, int channel, LiveWind
* Actuators are handled through callbacks on their value changing from the
* SmartDashboard widgets.
*/
void LiveWindow::UpdateValues()
{
for (unsigned int i = 0; i < m_sensors.size(); i++)
{
m_sensors[i]->UpdateTable();
}
void LiveWindow::UpdateValues() {
for (unsigned int i = 0; i < m_sensors.size(); i++) {
m_sensors[i]->UpdateTable();
}
}
/**
* This method is called periodically to cause the sensors to send new values
* to the SmartDashboard.
*/
void LiveWindow::Run()
{
if (m_enabled)
{
UpdateValues();
}
void LiveWindow::Run() {
if (m_enabled) {
UpdateValues();
}
}
/**
* Initialize all the LiveWindow elements the first time we enter LiveWindow mode.
* By holding off creating the NetworkTable entries, it allows them to be redefined
* before the first time in LiveWindow mode. This allows default sensor and actuator
* values to be created that are replaced with the custom names from users calling
* Initialize all the LiveWindow elements the first time we enter LiveWindow
* mode.
* By holding off creating the NetworkTable entries, it allows them to be
* redefined
* before the first time in LiveWindow mode. This allows default sensor and
* actuator
* values to be created that are replaced with the custom names from users
* calling
* addActuator and addSensor.
*/
void LiveWindow::InitializeLiveWindowComponents()
{
for (std::map<LiveWindowSendable *, LiveWindowComponent>::iterator it =
m_components.begin(); it != m_components.end(); ++it)
{
LiveWindowSendable *component = it->first;
LiveWindowComponent c = it->second;
std::string subsystem = c.subsystem;
std::string name = c.name;
m_liveWindowTable->GetSubTable(subsystem)->PutString("~TYPE~",
"LW Subsystem");
ITable *table = m_liveWindowTable->GetSubTable(subsystem)->GetSubTable(
name);
table->PutString("~TYPE~", component->GetSmartDashboardType());
table->PutString("Name", name);
table->PutString("Subsystem", subsystem);
component->InitTable(table);
if (c.isSensor)
{
m_sensors.push_back(component);
}
}
void LiveWindow::InitializeLiveWindowComponents() {
for (std::map<LiveWindowSendable *, LiveWindowComponent>::iterator it =
m_components.begin();
it != m_components.end(); ++it) {
LiveWindowSendable *component = it->first;
LiveWindowComponent c = it->second;
std::string subsystem = c.subsystem;
std::string name = c.name;
m_liveWindowTable->GetSubTable(subsystem)
->PutString("~TYPE~", "LW Subsystem");
ITable *table =
m_liveWindowTable->GetSubTable(subsystem)->GetSubTable(name);
table->PutString("~TYPE~", component->GetSmartDashboardType());
table->PutString("Name", name);
table->PutString("Subsystem", subsystem);
component->InitTable(table);
if (c.isSensor) {
m_sensors.push_back(component);
}
}
}

View File

@@ -1,7 +1,6 @@
#include "LiveWindow/LiveWindowStatusListener.h"
#include "Commands/Scheduler.h"
void LiveWindowStatusListener::ValueChanged(ITable* source, const std::string& key, EntryValue value, bool isNew) {
}
void LiveWindowStatusListener::ValueChanged(ITable* source,
const std::string& key,
EntryValue value, bool isNew) {}

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Copyright (c) FIRST 2008. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -12,18 +13,18 @@ ReentrantSemaphore Resource::m_createLock;
/**
* Allocate storage for a new instance of Resource.
* Allocate a bool array of values that will get initialized to indicate that no resources
* have been allocated yet. The indicies of the resources are [0 .. elements - 1].
* Allocate a bool array of values that will get initialized to indicate that no
* resources
* have been allocated yet. The indicies of the resources are [0 .. elements -
* 1].
*/
Resource::Resource(uint32_t elements)
{
Synchronized sync(m_createLock);
m_size = elements;
m_isAllocated = new bool[m_size];
for (uint32_t i=0; i < m_size; i++)
{
m_isAllocated[i] = false;
}
Resource::Resource(uint32_t elements) {
Synchronized sync(m_createLock);
m_size = elements;
m_isAllocated = new bool[m_size];
for (uint32_t i = 0; i < m_size; i++) {
m_isAllocated[i] = false;
}
}
/**
@@ -36,85 +37,76 @@ Resource::Resource(uint32_t elements)
* track, that is, it will allocate resource numbers in the range
* [0 .. elements - 1].
*/
/*static*/ void Resource::CreateResourceObject(Resource **r, uint32_t elements)
{
Synchronized sync(m_createLock);
if (*r == NULL)
{
*r = new Resource(elements);
}
/*static*/ void Resource::CreateResourceObject(Resource **r,
uint32_t elements) {
Synchronized sync(m_createLock);
if (*r == NULL) {
*r = new Resource(elements);
}
}
/**
* Delete the allocated array or resources.
* This happens when the module is unloaded (provided it was statically allocated).
* This happens when the module is unloaded (provided it was statically
* allocated).
*/
Resource::~Resource()
{
delete[] m_isAllocated;
}
Resource::~Resource() { delete[] m_isAllocated; }
/**
* Allocate a resource.
* When a resource is requested, mark it allocated. In this case, a free resource value
* When a resource is requested, mark it allocated. In this case, a free
* resource value
* within the range is located and returned after it is marked allocated.
*/
uint32_t Resource::Allocate(const char *resourceDesc)
{
Synchronized sync(m_allocateLock);
for (uint32_t i=0; i < m_size; i++)
{
if (!m_isAllocated[i])
{
m_isAllocated[i] = true;
return i;
}
}
wpi_setWPIErrorWithContext(NoAvailableResources, resourceDesc);
return ~0ul;
uint32_t Resource::Allocate(const char *resourceDesc) {
Synchronized sync(m_allocateLock);
for (uint32_t i = 0; i < m_size; i++) {
if (!m_isAllocated[i]) {
m_isAllocated[i] = true;
return i;
}
}
wpi_setWPIErrorWithContext(NoAvailableResources, resourceDesc);
return ~0ul;
}
/**
* Allocate a specific resource value.
* The user requests a specific resource value, i.e. channel number and it is verified
* The user requests a specific resource value, i.e. channel number and it is
* verified
* unallocated, then returned.
*/
uint32_t Resource::Allocate(uint32_t index, const char *resourceDesc)
{
Synchronized sync(m_allocateLock);
if (index >= m_size)
{
wpi_setWPIErrorWithContext(ChannelIndexOutOfRange, resourceDesc);
return ~0ul;
}
if ( m_isAllocated[index] )
{
wpi_setWPIErrorWithContext(ResourceAlreadyAllocated, resourceDesc);
return ~0ul;
}
m_isAllocated[index] = true;
return index;
uint32_t Resource::Allocate(uint32_t index, const char *resourceDesc) {
Synchronized sync(m_allocateLock);
if (index >= m_size) {
wpi_setWPIErrorWithContext(ChannelIndexOutOfRange, resourceDesc);
return ~0ul;
}
if (m_isAllocated[index]) {
wpi_setWPIErrorWithContext(ResourceAlreadyAllocated, resourceDesc);
return ~0ul;
}
m_isAllocated[index] = true;
return index;
}
/**
* Free an allocated resource.
* After a resource is no longer needed, for example a destructor is called for a channel assignment
* class, Free will release the resource value so it can be reused somewhere else in the program.
* After a resource is no longer needed, for example a destructor is called for
* a channel assignment
* class, Free will release the resource value so it can be reused somewhere
* else in the program.
*/
void Resource::Free(uint32_t index)
{
Synchronized sync(m_allocateLock);
if (index == ~0ul) return;
if (index >= m_size)
{
wpi_setWPIError(NotAllocated);
return;
}
if (!m_isAllocated[index])
{
wpi_setWPIError(NotAllocated);
return;
}
m_isAllocated[index] = false;
void Resource::Free(uint32_t index) {
Synchronized sync(m_allocateLock);
if (index == ~0ul) return;
if (index >= m_size) {
wpi_setWPIError(NotAllocated);
return;
}
if (!m_isAllocated[index]) {
wpi_setWPIError(NotAllocated);
return;
}
m_isAllocated[index] = false;
}

View File

@@ -2,41 +2,39 @@
RobotStateInterface* RobotState::impl = 0;
void RobotState::SetImplementation(RobotStateInterface* i) {
impl = i;
}
void RobotState::SetImplementation(RobotStateInterface* i) { impl = i; }
bool RobotState::IsDisabled() {
if (impl != nullptr) {
return impl->IsDisabled();
}
return true;
if (impl != nullptr) {
return impl->IsDisabled();
}
return true;
}
bool RobotState::IsEnabled() {
if (impl != nullptr) {
return impl->IsEnabled();
}
return false;
if (impl != nullptr) {
return impl->IsEnabled();
}
return false;
}
bool RobotState::IsOperatorControl() {
if (impl != nullptr) {
return impl->IsOperatorControl();
}
return true;
if (impl != nullptr) {
return impl->IsOperatorControl();
}
return true;
}
bool RobotState::IsAutonomous() {
if (impl != nullptr) {
return impl->IsAutonomous();
}
return false;
if (impl != nullptr) {
return impl->IsAutonomous();
}
return false;
}
bool RobotState::IsTest() {
if (impl != nullptr) {
return impl->IsTest();
}
return false;
if (impl != nullptr) {
return impl->IsTest();
}
return false;
}

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -13,66 +14,62 @@ static const char *kDefault = "default";
static const char *kOptions = "options";
static const char *kSelected = "selected";
SendableChooser::SendableChooser()
{
m_defaultChoice = "";
}
SendableChooser::SendableChooser() { m_defaultChoice = ""; }
/**
* Adds the given object to the list of options. On the {@link SmartDashboard} on the desktop,
* Adds the given object to the list of options. On the {@link SmartDashboard}
* on the desktop,
* the object will appear as the given name.
* @param name the name of the option
* @param object the option
*/
void SendableChooser::AddObject(const char *name, void *object)
{
m_choices[name] = object;
void SendableChooser::AddObject(const char *name, void *object) {
m_choices[name] = object;
}
/**
* Add the given object to the list of options and marks it as the default.
* Functionally, this is very close to {@link SendableChooser#AddObject(const char *name, void *object) AddObject(...)}
* except that it will use this as the default option if none other is explicitly selected.
* Functionally, this is very close to {@link SendableChooser#AddObject(const
* char *name, void *object) AddObject(...)}
* except that it will use this as the default option if none other is
* explicitly selected.
* @param name the name of the option
* @param object the option
*/
void SendableChooser::AddDefault(const char *name, void *object)
{
m_defaultChoice = name;
AddObject(name, object);
void SendableChooser::AddDefault(const char *name, void *object) {
m_defaultChoice = name;
AddObject(name, object);
}
/**
* Returns the selected option. If there is none selected, it will return the default. If there is none selected
* Returns the selected option. If there is none selected, it will return the
* default. If there is none selected
* and no default, then it will return {@code NULL}.
* @return the option selected
*/
void *SendableChooser::GetSelected()
{
std::string selected = m_table->GetString(kSelected, m_defaultChoice);
if (selected == "")
return NULL;
else
return m_choices[selected];
void *SendableChooser::GetSelected() {
std::string selected = m_table->GetString(kSelected, m_defaultChoice);
if (selected == "")
return NULL;
else
return m_choices[selected];
}
void SendableChooser::InitTable(ITable* subtable) {
StringArray keys;
m_table = subtable;
if (m_table != NULL) {
std::map<std::string, void *>::iterator iter;
for (iter = m_choices.begin(); iter != m_choices.end(); iter++) {
keys.add(iter->first);
}
m_table->PutValue(kOptions, keys);
m_table->PutString(kDefault, m_defaultChoice);
}
void SendableChooser::InitTable(ITable *subtable) {
StringArray keys;
m_table = subtable;
if (m_table != NULL) {
std::map<std::string, void *>::iterator iter;
for (iter = m_choices.begin(); iter != m_choices.end(); iter++) {
keys.add(iter->first);
}
m_table->PutValue(kOptions, keys);
m_table->PutString(kDefault, m_defaultChoice);
}
}
ITable* SendableChooser::GetTable() const {
return m_table;
}
ITable *SendableChooser::GetTable() const { return m_table; }
std::string SendableChooser::GetSmartDashboardType() const {
return "String Chooser";
return "String Chooser";
}

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -12,49 +13,48 @@
#include "networktables/NetworkTable.h"
#include "HLUsageReporting.h"
ITable* SmartDashboard::m_table = NULL;
ITable *SmartDashboard::m_table = NULL;
std::map<ITable *, Sendable *> SmartDashboard::m_tablesToData;
void SmartDashboard::init(){
m_table = NetworkTable::GetTable("SmartDashboard");
void SmartDashboard::init() {
m_table = NetworkTable::GetTable("SmartDashboard");
HLUsageReporting::ReportSmartDashboard();
HLUsageReporting::ReportSmartDashboard();
}
/**
* Maps the specified key to the specified value in this table.
* The key can not be NULL.
* The value can be retrieved by calling the get method with a key that is equal to the original key.
* The value can be retrieved by calling the get method with a key that is equal
* to the original key.
* @param keyName the key
* @param value the value
*/
void SmartDashboard::PutData(std::string key, Sendable *data)
{
if (data == NULL)
{
wpi_setGlobalWPIErrorWithContext(NullParameter, "value");
return;
}
ITable* dataTable = m_table->GetSubTable(key);
dataTable->PutString("~TYPE~", data->GetSmartDashboardType());
data->InitTable(dataTable);
m_tablesToData[dataTable] = data;
void SmartDashboard::PutData(std::string key, Sendable *data) {
if (data == NULL) {
wpi_setGlobalWPIErrorWithContext(NullParameter, "value");
return;
}
ITable *dataTable = m_table->GetSubTable(key);
dataTable->PutString("~TYPE~", data->GetSmartDashboardType());
data->InitTable(dataTable);
m_tablesToData[dataTable] = data;
}
/**
* Maps the specified key (where the key is the name of the {@link SmartDashboardNamedData}
* Maps the specified key (where the key is the name of the {@link
* SmartDashboardNamedData}
* to the specified value in this table.
* The value can be retrieved by calling the get method with a key that is equal to the original key.
* The value can be retrieved by calling the get method with a key that is equal
* to the original key.
* @param value the value
*/
void SmartDashboard::PutData(NamedSendable *value)
{
if (value == NULL)
{
wpi_setGlobalWPIErrorWithContext(NullParameter, "value");
return;
}
PutData(value->GetName(), value);
void SmartDashboard::PutData(NamedSendable *value) {
if (value == NULL) {
wpi_setGlobalWPIErrorWithContext(NullParameter, "value");
return;
}
PutData(value->GetName(), value);
}
/**
@@ -62,114 +62,114 @@ void SmartDashboard::PutData(NamedSendable *value)
* @param keyName the key
* @return the value
*/
Sendable *SmartDashboard::GetData(std::string key)
{
ITable* subtable = m_table->GetSubTable(key);
Sendable *data = m_tablesToData[subtable];
if (data == NULL)
{
wpi_setGlobalWPIErrorWithContext(SmartDashboardMissingKey, key.c_str());
return NULL;
}
return data;
Sendable *SmartDashboard::GetData(std::string key) {
ITable *subtable = m_table->GetSubTable(key);
Sendable *data = m_tablesToData[subtable];
if (data == NULL) {
wpi_setGlobalWPIErrorWithContext(SmartDashboardMissingKey, key.c_str());
return NULL;
}
return data;
}
/**
* Maps the specified key to the specified complex value (such as an array) in this table.
* Maps the specified key to the specified complex value (such as an array) in
* this table.
* The key can not be NULL.
* The value can be retrieved by calling the RetrieveValue method with a key that is equal to the original key.
* The value can be retrieved by calling the RetrieveValue method with a key
* that is equal to the original key.
* @param keyName the key
* @param value the value
*/
void SmartDashboard::PutValue(std::string keyName, ComplexData& value)
{
m_table->PutValue(keyName, value);
void SmartDashboard::PutValue(std::string keyName, ComplexData &value) {
m_table->PutValue(keyName, value);
}
/**
* Retrieves the complex value (such as an array) in this table into the complex data object
* Retrieves the complex value (such as an array) in this table into the complex
* data object
* The key can not be NULL.
* @param keyName the key
* @param value the object to retrieve the value into
*/
void SmartDashboard::RetrieveValue(std::string keyName, ComplexData& value)
{
m_table->RetrieveValue(keyName, value);
void SmartDashboard::RetrieveValue(std::string keyName, ComplexData &value) {
m_table->RetrieveValue(keyName, value);
}
/**
* Maps the specified key to the specified value in this table.
* The key can not be NULL.
* The value can be retrieved by calling the get method with a key that is equal to the original key.
* The value can be retrieved by calling the get method with a key that is equal
* to the original key.
* @param keyName the key
* @param value the value
*/
void SmartDashboard::PutBoolean(std::string keyName, bool value)
{
m_table->PutBoolean(keyName, value);
void SmartDashboard::PutBoolean(std::string keyName, bool value) {
m_table->PutBoolean(keyName, value);
}
/**
* Returns the value at the specified key. Throws an exception if the key is not found in the table
* Returns the value at the specified key. Throws an exception if the key is not
* found in the table
* @param keyName the key
* @return the value
*/
bool SmartDashboard::GetBoolean(std::string keyName)
{
return m_table->GetBoolean(keyName);
bool SmartDashboard::GetBoolean(std::string keyName) {
return m_table->GetBoolean(keyName);
}
/**
* Returns the value at the specified key. If the key is not found, returns the default value.
* Returns the value at the specified key. If the key is not found, returns the
* default value.
* @param keyName the key
* @return the value
*/
bool SmartDashboard::GetBoolean(std::string keyName, bool defaultValue)
{
return m_table->GetBoolean(keyName, defaultValue);
bool SmartDashboard::GetBoolean(std::string keyName, bool defaultValue) {
return m_table->GetBoolean(keyName, defaultValue);
}
/**
* Maps the specified key to the specified value in this table.
* The key can not be NULL.
* The value can be retrieved by calling the get method with a key that is equal to the original key.
* The value can be retrieved by calling the get method with a key that is equal
* to the original key.
* @param keyName the key
* @param value the value
*/
void SmartDashboard::PutNumber(std::string keyName, double value){
m_table->PutNumber(keyName, value);
void SmartDashboard::PutNumber(std::string keyName, double value) {
m_table->PutNumber(keyName, value);
}
/**
* Returns the value at the specified key. Throws an exception if the key is not found in the table.
* Returns the value at the specified key. Throws an exception if the key is not
* found in the table.
* @param keyName the key
* @return the value
*/
double SmartDashboard::GetNumber(std::string keyName)
{
return m_table->GetNumber(keyName);
double SmartDashboard::GetNumber(std::string keyName) {
return m_table->GetNumber(keyName);
}
/**
* Returns the value at the specified key. If the key is not found, returns the default value.
* Returns the value at the specified key. If the key is not found, returns the
* default value.
* @param keyName the key
* @return the value
*/
double SmartDashboard::GetNumber(std::string keyName, double defaultValue)
{
return m_table->GetNumber(keyName, defaultValue);
double SmartDashboard::GetNumber(std::string keyName, double defaultValue) {
return m_table->GetNumber(keyName, defaultValue);
}
/**
* Maps the specified key to the specified value in this table.
* Neither the key nor the value can be NULL.
* The value can be retrieved by calling the get method with a key that is equal to the original key.
* The value can be retrieved by calling the get method with a key that is equal
* to the original key.
* @param keyName the key
* @param value the value
*/
void SmartDashboard::PutString(std::string keyName, std::string value)
{
m_table->PutString(keyName, value);
void SmartDashboard::PutString(std::string keyName, std::string value) {
m_table->PutString(keyName, value);
}
/**
@@ -179,32 +179,33 @@ void SmartDashboard::PutString(std::string keyName, std::string value)
* @param valueLen the size of the buffer pointed to by value
* @return the length of the string
*/
int SmartDashboard::GetString(std::string keyName, char *outBuffer, unsigned int bufferLen){
std::string value = m_table->GetString(keyName);
unsigned int i;
for(i = 0; i<bufferLen-1&&i<value.length(); ++i)
outBuffer[i] = (char)value.at(i);
outBuffer[i] = '\0';
return i;
}
/**
* Returns the value at the specified key. Throws an exception if the key is not found in the table
* @param keyName the key
* @return the value
*/
std::string SmartDashboard::GetString(std::string keyName)
{
return m_table->GetString(keyName);
int SmartDashboard::GetString(std::string keyName, char *outBuffer,
unsigned int bufferLen) {
std::string value = m_table->GetString(keyName);
unsigned int i;
for (i = 0; i < bufferLen - 1 && i < value.length(); ++i)
outBuffer[i] = (char)value.at(i);
outBuffer[i] = '\0';
return i;
}
/**
* Returns the value at the specified key. If the key is not found, returns the default value.
* Returns the value at the specified key. Throws an exception if the key is not
* found in the table
* @param keyName the key
* @return the value
*/
std::string SmartDashboard::GetString(std::string keyName, std::string defaultValue)
{
return m_table->GetString(keyName, defaultValue);
std::string SmartDashboard::GetString(std::string keyName) {
return m_table->GetString(keyName);
}
/**
* Returns the value at the specified key. If the key is not found, returns the
* default value.
* @param keyName the key
* @return the value
*/
std::string SmartDashboard::GetString(std::string keyName,
std::string defaultValue) {
return m_table->GetString(keyName, defaultValue);
}

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Copyright (c) FIRST 2008. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -12,52 +13,64 @@
/**
* ADXL345 Accelerometer on I2C.
*
* This class allows access to a Analog Devices ADXL345 3-axis accelerometer on an I2C bus.
* This class assumes the default (not alternate) sensor address of 0x1D (7-bit address).
* This class allows access to a Analog Devices ADXL345 3-axis accelerometer on
* an I2C bus.
* This class assumes the default (not alternate) sensor address of 0x1D (7-bit
* address).
*/
class ADXL345_I2C : public Accelerometer, public I2C, public LiveWindowSendable
{
protected:
static const uint8_t kAddress = 0x1D;
static const uint8_t kPowerCtlRegister = 0x2D;
static const uint8_t kDataFormatRegister = 0x31;
static const uint8_t kDataRegister = 0x32;
static constexpr double kGsPerLSB = 0.00390625;
enum PowerCtlFields {kPowerCtl_Link=0x20, kPowerCtl_AutoSleep=0x10, kPowerCtl_Measure=0x08, kPowerCtl_Sleep=0x04};
enum DataFormatFields {kDataFormat_SelfTest=0x80, kDataFormat_SPI=0x40, kDataFormat_IntInvert=0x20,
kDataFormat_FullRes=0x08, kDataFormat_Justify=0x04};
class ADXL345_I2C : public Accelerometer,
public I2C,
public LiveWindowSendable {
protected:
static const uint8_t kAddress = 0x1D;
static const uint8_t kPowerCtlRegister = 0x2D;
static const uint8_t kDataFormatRegister = 0x31;
static const uint8_t kDataRegister = 0x32;
static constexpr double kGsPerLSB = 0.00390625;
enum PowerCtlFields {
kPowerCtl_Link = 0x20,
kPowerCtl_AutoSleep = 0x10,
kPowerCtl_Measure = 0x08,
kPowerCtl_Sleep = 0x04
};
enum DataFormatFields {
kDataFormat_SelfTest = 0x80,
kDataFormat_SPI = 0x40,
kDataFormat_IntInvert = 0x20,
kDataFormat_FullRes = 0x08,
kDataFormat_Justify = 0x04
};
public:
enum Axes {kAxis_X=0x00, kAxis_Y=0x02, kAxis_Z=0x04};
struct AllAxes
{
double XAxis;
double YAxis;
double ZAxis;
};
public:
enum Axes { kAxis_X = 0x00, kAxis_Y = 0x02, kAxis_Z = 0x04 };
struct AllAxes {
double XAxis;
double YAxis;
double ZAxis;
};
public:
explicit ADXL345_I2C(Port port, Range range = kRange_2G);
virtual ~ADXL345_I2C();
public:
explicit ADXL345_I2C(Port port, Range range = kRange_2G);
virtual ~ADXL345_I2C();
// Accelerometer interface
virtual void SetRange(Range range) override;
virtual double GetX() override;
virtual double GetY() override;
virtual double GetZ() override;
// Accelerometer interface
virtual void SetRange(Range range) override;
virtual double GetX() override;
virtual double GetY() override;
virtual double GetZ() override;
virtual double GetAcceleration(Axes axis);
virtual AllAxes GetAccelerations();
virtual double GetAcceleration(Axes axis);
virtual AllAxes GetAccelerations();
virtual std::string GetSmartDashboardType() const override;
virtual void InitTable(ITable *subtable) override;
virtual void UpdateTable() override;
virtual ITable* GetTable() const override;
virtual void StartLiveWindowMode() override {}
virtual void StopLiveWindowMode() override {}
virtual std::string GetSmartDashboardType() const override;
virtual void InitTable(ITable *subtable) override;
virtual void UpdateTable() override;
virtual ITable *GetTable() const override;
virtual void StartLiveWindowMode() override {}
virtual void StopLiveWindowMode() override {}
protected:
//I2C* m_i2c;
private:
ITable *m_table;
protected:
// I2C* m_i2c;
private:
ITable *m_table;
};

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Copyright (c) FIRST 2008. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -16,55 +17,67 @@ class DigitalOutput;
/**
* ADXL345 Accelerometer on SPI.
*
* This class allows access to an Analog Devices ADXL345 3-axis accelerometer via SPI.
* This class allows access to an Analog Devices ADXL345 3-axis accelerometer
* via SPI.
* This class assumes the sensor is wired in 4-wire SPI mode.
*/
class ADXL345_SPI : public Accelerometer, public SensorBase, public LiveWindowSendable
{
protected:
static const uint8_t kPowerCtlRegister = 0x2D;
static const uint8_t kDataFormatRegister = 0x31;
static const uint8_t kDataRegister = 0x32;
static constexpr double kGsPerLSB = 0.00390625;
enum SPIAddressFields {kAddress_Read=0x80, kAddress_MultiByte=0x40};
enum PowerCtlFields {kPowerCtl_Link=0x20, kPowerCtl_AutoSleep=0x10, kPowerCtl_Measure=0x08, kPowerCtl_Sleep=0x04};
enum DataFormatFields {kDataFormat_SelfTest=0x80, kDataFormat_SPI=0x40, kDataFormat_IntInvert=0x20,
kDataFormat_FullRes=0x08, kDataFormat_Justify=0x04};
class ADXL345_SPI : public Accelerometer,
public SensorBase,
public LiveWindowSendable {
protected:
static const uint8_t kPowerCtlRegister = 0x2D;
static const uint8_t kDataFormatRegister = 0x31;
static const uint8_t kDataRegister = 0x32;
static constexpr double kGsPerLSB = 0.00390625;
enum SPIAddressFields { kAddress_Read = 0x80, kAddress_MultiByte = 0x40 };
enum PowerCtlFields {
kPowerCtl_Link = 0x20,
kPowerCtl_AutoSleep = 0x10,
kPowerCtl_Measure = 0x08,
kPowerCtl_Sleep = 0x04
};
enum DataFormatFields {
kDataFormat_SelfTest = 0x80,
kDataFormat_SPI = 0x40,
kDataFormat_IntInvert = 0x20,
kDataFormat_FullRes = 0x08,
kDataFormat_Justify = 0x04
};
public:
enum Axes {kAxis_X=0x00, kAxis_Y=0x02, kAxis_Z=0x04};
struct AllAxes
{
double XAxis;
double YAxis;
double ZAxis;
};
public:
enum Axes { kAxis_X = 0x00, kAxis_Y = 0x02, kAxis_Z = 0x04 };
struct AllAxes {
double XAxis;
double YAxis;
double ZAxis;
};
public:
ADXL345_SPI(SPI::Port port, Range range=kRange_2G);
virtual ~ADXL345_SPI();
public:
ADXL345_SPI(SPI::Port port, Range range = kRange_2G);
virtual ~ADXL345_SPI();
// Accelerometer interface
virtual void SetRange(Range range) override;
virtual double GetX() override;
virtual double GetY() override;
virtual double GetZ() override;
// Accelerometer interface
virtual void SetRange(Range range) override;
virtual double GetX() override;
virtual double GetY() override;
virtual double GetZ() override;
virtual double GetAcceleration(Axes axis);
virtual AllAxes GetAccelerations();
virtual double GetAcceleration(Axes axis);
virtual AllAxes GetAccelerations();
virtual std::string GetSmartDashboardType() const override;
virtual void InitTable(ITable *subtable) override;
virtual void UpdateTable() override;
virtual ITable* GetTable() const override;
virtual void StartLiveWindowMode() override {}
virtual void StopLiveWindowMode() override {}
virtual std::string GetSmartDashboardType() const override;
virtual void InitTable(ITable* subtable) override;
virtual void UpdateTable() override;
virtual ITable* GetTable() const override;
virtual void StartLiveWindowMode() override {}
virtual void StopLiveWindowMode() override {}
protected:
void Init(Range range);
protected:
void Init(Range range);
SPI* m_spi;
SPI::Port m_port;
private:
ITable *m_table;
SPI* m_spi;
SPI::Port m_port;
private:
ITable* m_table;
};

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Copyright (c) FIRST 2008. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -12,35 +13,39 @@
/**
* Handle operation of an analog accelerometer.
* The accelerometer reads acceleration directly through the sensor. Many sensors have
* multiple axis and can be treated as multiple devices. Each is calibrated by finding
* The accelerometer reads acceleration directly through the sensor. Many
* sensors have
* multiple axis and can be treated as multiple devices. Each is calibrated by
* finding
* the center value over a period of time.
*/
class AnalogAccelerometer : public SensorBase, public PIDSource, public LiveWindowSendable {
public:
explicit AnalogAccelerometer(int32_t channel);
explicit AnalogAccelerometer(AnalogInput *channel);
virtual ~AnalogAccelerometer();
class AnalogAccelerometer : public SensorBase,
public PIDSource,
public LiveWindowSendable {
public:
explicit AnalogAccelerometer(int32_t channel);
explicit AnalogAccelerometer(AnalogInput *channel);
virtual ~AnalogAccelerometer();
float GetAcceleration() const;
void SetSensitivity(float sensitivity);
void SetZero(float zero);
double PIDGet() const override;
float GetAcceleration() const;
void SetSensitivity(float sensitivity);
void SetZero(float zero);
double PIDGet() const override;
void UpdateTable() override;
void StartLiveWindowMode() override;
void StopLiveWindowMode() override;
std::string GetSmartDashboardType() const override;
void InitTable(ITable *subTable) override;
ITable * GetTable() const override;
void UpdateTable() override;
void StartLiveWindowMode() override;
void StopLiveWindowMode() override;
std::string GetSmartDashboardType() const override;
void InitTable(ITable *subTable) override;
ITable *GetTable() const override;
private:
void InitAccelerometer();
private:
void InitAccelerometer();
AnalogInput *m_AnalogInput;
float m_voltsPerG;
float m_zeroGVoltage;
bool m_allocatedChannel;
AnalogInput *m_AnalogInput;
float m_voltsPerG;
float m_zeroGVoltage;
bool m_allocatedChannel;
ITable *m_table;
ITable *m_table;
};

View File

@@ -13,66 +13,72 @@
/**
* Analog input class.
*
* Connected to each analog channel is an averaging and oversampling engine. This engine accumulates
* the specified ( by SetAverageBits() and SetOversampleBits() ) number of samples before returning a new
* value. This is not a sliding window average. The only difference between the oversampled samples and
* the averaged samples is that the oversampled samples are simply accumulated effectively increasing the
* resolution, while the averaged samples are divided by the number of samples to retain the resolution,
* Connected to each analog channel is an averaging and oversampling engine.
* This engine accumulates
* the specified ( by SetAverageBits() and SetOversampleBits() ) number of
* samples before returning a new
* value. This is not a sliding window average. The only difference between
* the oversampled samples and
* the averaged samples is that the oversampled samples are simply accumulated
* effectively increasing the
* resolution, while the averaged samples are divided by the number of samples
* to retain the resolution,
* but get more stable values.
*/
class AnalogInput : public SensorBase, public PIDSource, public LiveWindowSendable
{
public:
static const uint8_t kAccumulatorModuleNumber = 1;
static const uint32_t kAccumulatorNumChannels = 2;
static const uint32_t kAccumulatorChannels[kAccumulatorNumChannels];
class AnalogInput : public SensorBase,
public PIDSource,
public LiveWindowSendable {
public:
static const uint8_t kAccumulatorModuleNumber = 1;
static const uint32_t kAccumulatorNumChannels = 2;
static const uint32_t kAccumulatorChannels[kAccumulatorNumChannels];
explicit AnalogInput(uint32_t channel);
virtual ~AnalogInput();
explicit AnalogInput(uint32_t channel);
virtual ~AnalogInput();
int16_t GetValue() const;
int32_t GetAverageValue() const;
int16_t GetValue() const;
int32_t GetAverageValue() const;
float GetVoltage() const;
float GetAverageVoltage() const;
float GetVoltage() const;
float GetAverageVoltage() const;
uint32_t GetChannel() const;
uint32_t GetChannel() const;
void SetAverageBits(uint32_t bits);
uint32_t GetAverageBits() const;
void SetOversampleBits(uint32_t bits);
uint32_t GetOversampleBits() const;
void SetAverageBits(uint32_t bits);
uint32_t GetAverageBits() const;
void SetOversampleBits(uint32_t bits);
uint32_t GetOversampleBits() const;
uint32_t GetLSBWeight() const;
int32_t GetOffset() const;
uint32_t GetLSBWeight() const;
int32_t GetOffset() const;
bool IsAccumulatorChannel() const;
void InitAccumulator();
void SetAccumulatorInitialValue(int64_t value);
void ResetAccumulator();
void SetAccumulatorCenter(int32_t center);
void SetAccumulatorDeadband(int32_t deadband);
int64_t GetAccumulatorValue() const;
uint32_t GetAccumulatorCount() const;
void GetAccumulatorOutput(int64_t *value, uint32_t *count) const;
bool IsAccumulatorChannel() const;
void InitAccumulator();
void SetAccumulatorInitialValue(int64_t value);
void ResetAccumulator();
void SetAccumulatorCenter(int32_t center);
void SetAccumulatorDeadband(int32_t deadband);
int64_t GetAccumulatorValue() const;
uint32_t GetAccumulatorCount() const;
void GetAccumulatorOutput(int64_t *value, uint32_t *count) const;
static void SetSampleRate(float samplesPerSecond);
static float GetSampleRate();
static void SetSampleRate(float samplesPerSecond);
static float GetSampleRate();
double PIDGet() const override;
double PIDGet() const override;
void UpdateTable() override;
void StartLiveWindowMode() override;
void StopLiveWindowMode() override;
std::string GetSmartDashboardType() const override;
void InitTable(ITable *subTable) override;
ITable * GetTable() const override;
void UpdateTable() override;
void StartLiveWindowMode() override;
void StopLiveWindowMode() override;
std::string GetSmartDashboardType() const override;
void InitTable(ITable *subTable) override;
ITable *GetTable() const override;
private:
void InitAnalogInput(uint32_t channel);
uint32_t m_channel;
void* m_port;
int64_t m_accumulatorOffset;
private:
void InitAnalogInput(uint32_t channel);
uint32_t m_channel;
void *m_port;
int64_t m_accumulatorOffset;
ITable *m_table;
ITable *m_table;
};

View File

@@ -14,26 +14,25 @@
/**
* MXP analog output class.
*/
class AnalogOutput : public SensorBase, public LiveWindowSendable
{
public:
explicit AnalogOutput(uint32_t channel);
virtual ~AnalogOutput();
class AnalogOutput : public SensorBase, public LiveWindowSendable {
public:
explicit AnalogOutput(uint32_t channel);
virtual ~AnalogOutput();
void SetVoltage(float voltage);
float GetVoltage() const;
void SetVoltage(float voltage);
float GetVoltage() const;
void UpdateTable() override;
void StartLiveWindowMode() override;
void StopLiveWindowMode() override;
std::string GetSmartDashboardType() const override;
void InitTable(ITable *subTable) override;
ITable *GetTable() const override;
void UpdateTable() override;
void StartLiveWindowMode() override;
void StopLiveWindowMode() override;
std::string GetSmartDashboardType() const override;
void InitTable(ITable *subTable) override;
ITable *GetTable() const override;
protected:
void InitAnalogOutput(uint32_t channel);
uint32_t m_channel;
void* m_port;
protected:
void InitAnalogOutput(uint32_t channel);
uint32_t m_channel;
void *m_port;
ITable *m_table;
ITable *m_table;
};

View File

@@ -13,73 +13,78 @@
* @author Colby Skeggs (rail voltage)
*/
class AnalogPotentiometer : public Potentiometer, public LiveWindowSendable {
public:
/**
* AnalogPotentiometer constructor.
*
* Use the fullRange and offset values so that the output produces
* meaningful values. I.E: you have a 270 degree potentiometer and
* you want the output to be degrees with the halfway point as 0
* degrees. The fullRange value is 270.0(degrees) and the offset is
* -135.0 since the halfway point after scaling is 135 degrees.
*
* This will calculate the result from the fullRange times the
* fraction of the supply voltage, plus the offset.
*
* @param channel The analog channel this potentiometer is plugged into.
* @param fullRange The scaling to multiply the voltage by to get a meaningful unit.
* @param offset The offset to add to the scaled value for controlling the zero value
*/
explicit AnalogPotentiometer(int channel, double fullRange = 1.0, double offset = 0.0);
public:
/**
* AnalogPotentiometer constructor.
*
* Use the fullRange and offset values so that the output produces
* meaningful values. I.E: you have a 270 degree potentiometer and
* you want the output to be degrees with the halfway point as 0
* degrees. The fullRange value is 270.0(degrees) and the offset is
* -135.0 since the halfway point after scaling is 135 degrees.
*
* This will calculate the result from the fullRange times the
* fraction of the supply voltage, plus the offset.
*
* @param channel The analog channel this potentiometer is plugged into.
* @param fullRange The scaling to multiply the voltage by to get a meaningful
* unit.
* @param offset The offset to add to the scaled value for controlling the
* zero value
*/
explicit AnalogPotentiometer(int channel, double fullRange = 1.0,
double offset = 0.0);
explicit AnalogPotentiometer(AnalogInput *input, double fullRange = 1.0, double offset = 0.0);
explicit AnalogPotentiometer(AnalogInput *input, double fullRange = 1.0,
double offset = 0.0);
explicit AnalogPotentiometer(AnalogInput &input, double fullRange = 1.0, double offset = 0.0);
explicit AnalogPotentiometer(AnalogInput &input, double fullRange = 1.0,
double offset = 0.0);
virtual ~AnalogPotentiometer();
virtual ~AnalogPotentiometer();
/**
* Get the current reading of the potentiomer.
*
* @return The current position of the potentiometer.
*/
virtual double Get() const override;
/**
* Get the current reading of the potentiomer.
*
* @return The current position of the potentiometer.
*/
virtual double Get() const override;
/**
* Implement the PIDSource interface.
*
* @return The current reading.
*/
virtual double PIDGet() const override;
/**
* Implement the PIDSource interface.
*
* @return The current reading.
*/
virtual double PIDGet() const override;
/*
* Live Window code, only does anything if live window is activated.
*/
virtual std::string GetSmartDashboardType() const override;
virtual void InitTable(ITable *subtable) override;
virtual void UpdateTable() override;
virtual ITable *GetTable() const override;
/**
* AnalogPotentiometers don't have to do anything special when entering the
* LiveWindow.
*/
virtual void StartLiveWindowMode() override {}
/*
* Live Window code, only does anything if live window is activated.
*/
virtual std::string GetSmartDashboardType() const override;
virtual void InitTable(ITable *subtable) override;
virtual void UpdateTable() override;
virtual ITable* GetTable() const override;
/**
* AnalogPotentiometers don't have to do anything special when exiting the
* LiveWindow.
*/
virtual void StopLiveWindowMode() override {}
/**
* AnalogPotentiometers don't have to do anything special when entering the LiveWindow.
*/
virtual void StartLiveWindowMode() override {}
private:
double m_fullRange, m_offset;
AnalogInput *m_analog_input;
ITable *m_table;
bool m_init_analog_input;
/**
* AnalogPotentiometers don't have to do anything special when exiting the LiveWindow.
*/
virtual void StopLiveWindowMode() override {}
private:
double m_fullRange, m_offset;
AnalogInput* m_analog_input;
ITable* m_table;
bool m_init_analog_input;
/**
* Common initialization code called by all constructors.
*/
void initPot(AnalogInput *input, double fullRange, double offset);
/**
* Common initialization code called by all constructors.
*/
void initPot(AnalogInput *input, double fullRange, double offset);
};

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Copyright (c) FIRST 2008. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -11,26 +12,26 @@
class AnalogInput;
class AnalogTrigger : public SensorBase
{
friend class AnalogTriggerOutput;
public:
explicit AnalogTrigger(int32_t channel);
explicit AnalogTrigger(AnalogInput *channel);
virtual ~AnalogTrigger();
class AnalogTrigger : public SensorBase {
friend class AnalogTriggerOutput;
void SetLimitsVoltage(float lower, float upper);
void SetLimitsRaw(int32_t lower, int32_t upper);
void SetAveraged(bool useAveragedValue);
void SetFiltered(bool useFilteredValue);
uint32_t GetIndex();
bool GetInWindow();
bool GetTriggerState();
AnalogTriggerOutput *CreateOutput(AnalogTriggerType type);
public:
explicit AnalogTrigger(int32_t channel);
explicit AnalogTrigger(AnalogInput *channel);
virtual ~AnalogTrigger();
private:
void InitTrigger(uint32_t channel);
void SetLimitsVoltage(float lower, float upper);
void SetLimitsRaw(int32_t lower, int32_t upper);
void SetAveraged(bool useAveragedValue);
void SetFiltered(bool useFilteredValue);
uint32_t GetIndex();
bool GetInWindow();
bool GetTriggerState();
AnalogTriggerOutput *CreateOutput(AnalogTriggerType type);
uint8_t m_index;
void* m_trigger;
private:
void InitTrigger(uint32_t channel);
uint8_t m_index;
void *m_trigger;
};

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Copyright (c) FIRST 2008. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -11,47 +12,63 @@ class AnalogTrigger;
/**
* Class to represent a specific output from an analog trigger.
* This class is used to get the current output value and also as a DigitalSource
* This class is used to get the current output value and also as a
* DigitalSource
* to provide routing of an output to digital subsystems on the FPGA such as
* Counter, Encoder, and Interrupt.
*
* The TriggerState output indicates the primary output value of the trigger. If the analog
* signal is less than the lower limit, the output is false. If the analog value is greater
* than the upper limit, then the output is true. If the analog value is in between, then
* The TriggerState output indicates the primary output value of the trigger.
* If the analog
* signal is less than the lower limit, the output is false. If the analog
* value is greater
* than the upper limit, then the output is true. If the analog value is in
* between, then
* the trigger output state maintains its most recent value.
*
* The InWindow output indicates whether or not the analog signal is inside the range defined
* The InWindow output indicates whether or not the analog signal is inside the
* range defined
* by the limits.
*
* The RisingPulse and FallingPulse outputs detect an instantaneous transition from above the
* upper limit to below the lower limit, and vise versa. These pulses represent a rollover
* condition of a sensor and can be routed to an up / down couter or to interrupts. Because
* the outputs generate a pulse, they cannot be read directly. To help ensure that a rollover
* condition is not missed, there is an average rejection filter available that operates on the
* upper 8 bits of a 12 bit number and selects the nearest outlyer of 3 samples. This will reject
* a sample that is (due to averaging or sampling) errantly between the two limits. This filter
* will fail if more than one sample in a row is errantly in between the two limits. You may see
* this problem if attempting to use this feature with a mechanical rollover sensor, such as a
* 360 degree no-stop potentiometer without signal conditioning, because the rollover transition
* is not sharp / clean enough. Using the averaging engine may help with this, but rotational speeds of
* The RisingPulse and FallingPulse outputs detect an instantaneous transition
* from above the
* upper limit to below the lower limit, and vise versa. These pulses represent
* a rollover
* condition of a sensor and can be routed to an up / down couter or to
* interrupts. Because
* the outputs generate a pulse, they cannot be read directly. To help ensure
* that a rollover
* condition is not missed, there is an average rejection filter available that
* operates on the
* upper 8 bits of a 12 bit number and selects the nearest outlyer of 3 samples.
* This will reject
* a sample that is (due to averaging or sampling) errantly between the two
* limits. This filter
* will fail if more than one sample in a row is errantly in between the two
* limits. You may see
* this problem if attempting to use this feature with a mechanical rollover
* sensor, such as a
* 360 degree no-stop potentiometer without signal conditioning, because the
* rollover transition
* is not sharp / clean enough. Using the averaging engine may help with this,
* but rotational speeds of
* the sensor will then be limited.
*/
class AnalogTriggerOutput : public DigitalSource
{
friend class AnalogTrigger;
public:
class AnalogTriggerOutput : public DigitalSource {
friend class AnalogTrigger;
virtual ~AnalogTriggerOutput();
bool Get() const;
public:
virtual ~AnalogTriggerOutput();
bool Get() const;
// DigitalSource interface
virtual uint32_t GetChannelForRouting() const override;
virtual uint32_t GetModuleForRouting() const override;
virtual bool GetAnalogTriggerForRouting() const override;
protected:
AnalogTriggerOutput(AnalogTrigger *trigger, AnalogTriggerType outputType);
// DigitalSource interface
virtual uint32_t GetChannelForRouting() const override;
virtual uint32_t GetModuleForRouting() const override;
virtual bool GetAnalogTriggerForRouting() const override;
private:
AnalogTrigger *m_trigger;
AnalogTriggerType m_outputType;
protected:
AnalogTriggerOutput(AnalogTrigger *trigger, AnalogTriggerType outputType);
private:
AnalogTrigger *m_trigger;
AnalogTriggerType m_outputType;
};

View File

@@ -14,25 +14,26 @@
*
* This class allows access to the RoboRIO's internal accelerometer.
*/
class BuiltInAccelerometer : public Accelerometer, public SensorBase, public LiveWindowSendable
{
public:
BuiltInAccelerometer(Range range = kRange_8G);
virtual ~BuiltInAccelerometer();
class BuiltInAccelerometer : public Accelerometer,
public SensorBase,
public LiveWindowSendable {
public:
BuiltInAccelerometer(Range range = kRange_8G);
virtual ~BuiltInAccelerometer();
// Accelerometer interface
virtual void SetRange(Range range) override;
virtual double GetX() override;
virtual double GetY() override;
virtual double GetZ() override;
// Accelerometer interface
virtual void SetRange(Range range) override;
virtual double GetX() override;
virtual double GetY() override;
virtual double GetZ() override;
virtual std::string GetSmartDashboardType() const override;
virtual void InitTable(ITable *subtable) override;
virtual void UpdateTable() override;
virtual ITable* GetTable() const override;
virtual void StartLiveWindowMode() override {}
virtual void StopLiveWindowMode() override {}
virtual std::string GetSmartDashboardType() const override;
virtual void InitTable(ITable *subtable) override;
virtual void UpdateTable() override;
virtual ITable *GetTable() const override;
virtual void StartLiveWindowMode() override {}
virtual void StopLiveWindowMode() override {}
private:
ITable *m_table;
private:
ITable *m_table;
};

View File

@@ -16,36 +16,36 @@
// The masks of the fields that are used in the message identifier.
//
//*****************************************************************************
#define CAN_MSGID_FULL_M 0x1fffffff
#define CAN_MSGID_DEVNO_M 0x0000003f
#define CAN_MSGID_API_M 0x0000ffc0
#define CAN_MSGID_MFR_M 0x00ff0000
#define CAN_MSGID_DTYPE_M 0x1f000000
#define CAN_MSGID_DEVNO_S 0
#define CAN_MSGID_API_S 6
#define CAN_MSGID_MFR_S 16
#define CAN_MSGID_DTYPE_S 24
#define CAN_MSGID_FULL_M 0x1fffffff
#define CAN_MSGID_DEVNO_M 0x0000003f
#define CAN_MSGID_API_M 0x0000ffc0
#define CAN_MSGID_MFR_M 0x00ff0000
#define CAN_MSGID_DTYPE_M 0x1f000000
#define CAN_MSGID_DEVNO_S 0
#define CAN_MSGID_API_S 6
#define CAN_MSGID_MFR_S 16
#define CAN_MSGID_DTYPE_S 24
//*****************************************************************************
//
// The Reserved device number values in the Message Id.
//
//*****************************************************************************
#define CAN_MSGID_DEVNO_BCAST 0x00000000
#define CAN_MSGID_DEVNO_BCAST 0x00000000
//*****************************************************************************
//
// The Reserved system control API numbers in the Message Id.
//
//*****************************************************************************
#define CAN_MSGID_API_SYSHALT 0x00000000
#define CAN_MSGID_API_SYSRST 0x00000040
#define CAN_MSGID_API_SYSHALT 0x00000000
#define CAN_MSGID_API_SYSRST 0x00000040
#define CAN_MSGID_API_DEVASSIGN 0x00000080
#define CAN_MSGID_API_DEVQUERY 0x000000c0
#define CAN_MSGID_API_DEVQUERY 0x000000c0
#define CAN_MSGID_API_HEARTBEAT 0x00000140
#define CAN_MSGID_API_SYNC 0x00000180
#define CAN_MSGID_API_UPDATE 0x000001c0
#define CAN_MSGID_API_FIRMVER 0x00000200
#define CAN_MSGID_API_SYNC 0x00000180
#define CAN_MSGID_API_UPDATE 0x000001c0
#define CAN_MSGID_API_FIRMVER 0x00000200
#define CAN_MSGID_API_ENUMERATE 0x00000240
#define CAN_MSGID_API_SYSRESUME 0x00000280
@@ -54,44 +54,44 @@
// The 32 bit values associated with the CAN_MSGID_API_STATUS request.
//
//*****************************************************************************
#define CAN_STATUS_CODE_M 0x0000ffff
#define CAN_STATUS_MFG_M 0x00ff0000
#define CAN_STATUS_DTYPE_M 0x1f000000
#define CAN_STATUS_CODE_S 0
#define CAN_STATUS_MFG_S 16
#define CAN_STATUS_DTYPE_S 24
#define CAN_STATUS_CODE_M 0x0000ffff
#define CAN_STATUS_MFG_M 0x00ff0000
#define CAN_STATUS_DTYPE_M 0x1f000000
#define CAN_STATUS_CODE_S 0
#define CAN_STATUS_MFG_S 16
#define CAN_STATUS_DTYPE_S 24
//*****************************************************************************
//
// The Reserved manufacturer identifiers in the Message Id.
//
//*****************************************************************************
#define CAN_MSGID_MFR_NI 0x00010000
#define CAN_MSGID_MFR_LM 0x00020000
#define CAN_MSGID_MFR_DEKA 0x00030000
#define CAN_MSGID_MFR_NI 0x00010000
#define CAN_MSGID_MFR_LM 0x00020000
#define CAN_MSGID_MFR_DEKA 0x00030000
//*****************************************************************************
//
// The Reserved device type identifiers in the Message Id.
//
//*****************************************************************************
#define CAN_MSGID_DTYPE_BCAST 0x00000000
#define CAN_MSGID_DTYPE_ROBOT 0x01000000
#define CAN_MSGID_DTYPE_MOTOR 0x02000000
#define CAN_MSGID_DTYPE_RELAY 0x03000000
#define CAN_MSGID_DTYPE_GYRO 0x04000000
#define CAN_MSGID_DTYPE_ACCEL 0x05000000
#define CAN_MSGID_DTYPE_USONIC 0x06000000
#define CAN_MSGID_DTYPE_GEART 0x07000000
#define CAN_MSGID_DTYPE_UPDATE 0x1f000000
#define CAN_MSGID_DTYPE_BCAST 0x00000000
#define CAN_MSGID_DTYPE_ROBOT 0x01000000
#define CAN_MSGID_DTYPE_MOTOR 0x02000000
#define CAN_MSGID_DTYPE_RELAY 0x03000000
#define CAN_MSGID_DTYPE_GYRO 0x04000000
#define CAN_MSGID_DTYPE_ACCEL 0x05000000
#define CAN_MSGID_DTYPE_USONIC 0x06000000
#define CAN_MSGID_DTYPE_GEART 0x07000000
#define CAN_MSGID_DTYPE_UPDATE 0x1f000000
//*****************************************************************************
//
// LM Motor Control API Classes API Class and ID masks.
//
//*****************************************************************************
#define CAN_MSGID_API_CLASS_M 0x0000fc00
#define CAN_MSGID_API_ID_M 0x000003c0
#define CAN_MSGID_API_CLASS_M 0x0000fc00
#define CAN_MSGID_API_ID_M 0x000003c0
//*****************************************************************************
//
@@ -100,87 +100,84 @@
// the APIId.
//
//*****************************************************************************
#define CAN_API_MC_VOLTAGE 0x00000000
#define CAN_API_MC_SPD 0x00000400
#define CAN_API_MC_VCOMP 0x00000800
#define CAN_API_MC_POS 0x00000c00
#define CAN_API_MC_ICTRL 0x00001000
#define CAN_API_MC_STATUS 0x00001400
#define CAN_API_MC_PSTAT 0x00001800
#define CAN_API_MC_CFG 0x00001c00
#define CAN_API_MC_ACK 0x00002000
#define CAN_API_MC_VOLTAGE 0x00000000
#define CAN_API_MC_SPD 0x00000400
#define CAN_API_MC_VCOMP 0x00000800
#define CAN_API_MC_POS 0x00000c00
#define CAN_API_MC_ICTRL 0x00001000
#define CAN_API_MC_STATUS 0x00001400
#define CAN_API_MC_PSTAT 0x00001800
#define CAN_API_MC_CFG 0x00001c00
#define CAN_API_MC_ACK 0x00002000
//*****************************************************************************
//
// The Stellaris Motor Class Control Voltage API definitions.
//
//*****************************************************************************
#define LM_API_VOLT (CAN_MSGID_MFR_LM | CAN_MSGID_DTYPE_MOTOR | \
CAN_API_MC_VOLTAGE)
#define LM_API_VOLT_EN (LM_API_VOLT | (0 << CAN_MSGID_API_S))
#define LM_API_VOLT_DIS (LM_API_VOLT | (1 << CAN_MSGID_API_S))
#define LM_API_VOLT_SET (LM_API_VOLT | (2 << CAN_MSGID_API_S))
#define LM_API_VOLT_SET_RAMP (LM_API_VOLT | (3 << CAN_MSGID_API_S))
#define LM_API_VOLT \
(CAN_MSGID_MFR_LM | CAN_MSGID_DTYPE_MOTOR | CAN_API_MC_VOLTAGE)
#define LM_API_VOLT_EN (LM_API_VOLT | (0 << CAN_MSGID_API_S))
#define LM_API_VOLT_DIS (LM_API_VOLT | (1 << CAN_MSGID_API_S))
#define LM_API_VOLT_SET (LM_API_VOLT | (2 << CAN_MSGID_API_S))
#define LM_API_VOLT_SET_RAMP (LM_API_VOLT | (3 << CAN_MSGID_API_S))
//##### FIRST BEGIN #####
#define LM_API_VOLT_T_EN (LM_API_VOLT | (4 << CAN_MSGID_API_S))
#define LM_API_VOLT_T_SET (LM_API_VOLT | (5 << CAN_MSGID_API_S))
#define LM_API_VOLT_T_SET_NO_ACK \
(LM_API_VOLT | (7 << CAN_MSGID_API_S))
#define LM_API_VOLT_T_EN (LM_API_VOLT | (4 << CAN_MSGID_API_S))
#define LM_API_VOLT_T_SET (LM_API_VOLT | (5 << CAN_MSGID_API_S))
#define LM_API_VOLT_T_SET_NO_ACK (LM_API_VOLT | (7 << CAN_MSGID_API_S))
//##### FIRST END #####
#define LM_API_VOLT_SET_NO_ACK (LM_API_VOLT | (8 << CAN_MSGID_API_S))
#define LM_API_VOLT_SET_NO_ACK (LM_API_VOLT | (8 << CAN_MSGID_API_S))
//*****************************************************************************
//
// The Stellaris Motor Class Control API definitions for LM_API_VOLT_SET_RAMP.
//
//*****************************************************************************
#define LM_API_VOLT_RAMP_DIS 0
#define LM_API_VOLT_RAMP_DIS 0
//*****************************************************************************
//
// The Stellaris Motor Class Control API definitions for CAN_MSGID_API_SYNC.
//
//*****************************************************************************
#define LM_API_SYNC_PEND_NOW 0
#define LM_API_SYNC_PEND_NOW 0
//*****************************************************************************
//
// The Stellaris Motor Class Speed Control API definitions.
//
//*****************************************************************************
#define LM_API_SPD (CAN_MSGID_MFR_LM | CAN_MSGID_DTYPE_MOTOR | \
CAN_API_MC_SPD)
#define LM_API_SPD_EN (LM_API_SPD | (0 << CAN_MSGID_API_S))
#define LM_API_SPD_DIS (LM_API_SPD | (1 << CAN_MSGID_API_S))
#define LM_API_SPD_SET (LM_API_SPD | (2 << CAN_MSGID_API_S))
#define LM_API_SPD_PC (LM_API_SPD | (3 << CAN_MSGID_API_S))
#define LM_API_SPD_IC (LM_API_SPD | (4 << CAN_MSGID_API_S))
#define LM_API_SPD_DC (LM_API_SPD | (5 << CAN_MSGID_API_S))
#define LM_API_SPD_REF (LM_API_SPD | (6 << CAN_MSGID_API_S))
#define LM_API_SPD (CAN_MSGID_MFR_LM | CAN_MSGID_DTYPE_MOTOR | CAN_API_MC_SPD)
#define LM_API_SPD_EN (LM_API_SPD | (0 << CAN_MSGID_API_S))
#define LM_API_SPD_DIS (LM_API_SPD | (1 << CAN_MSGID_API_S))
#define LM_API_SPD_SET (LM_API_SPD | (2 << CAN_MSGID_API_S))
#define LM_API_SPD_PC (LM_API_SPD | (3 << CAN_MSGID_API_S))
#define LM_API_SPD_IC (LM_API_SPD | (4 << CAN_MSGID_API_S))
#define LM_API_SPD_DC (LM_API_SPD | (5 << CAN_MSGID_API_S))
#define LM_API_SPD_REF (LM_API_SPD | (6 << CAN_MSGID_API_S))
//##### FIRST BEGIN #####
#define LM_API_SPD_T_EN (LM_API_SPD | (7 << CAN_MSGID_API_S))
#define LM_API_SPD_T_SET (LM_API_SPD | (8 << CAN_MSGID_API_S))
#define LM_API_SPD_T_EN (LM_API_SPD | (7 << CAN_MSGID_API_S))
#define LM_API_SPD_T_SET (LM_API_SPD | (8 << CAN_MSGID_API_S))
#define LM_API_SPD_T_SET_NO_ACK (LM_API_SPD | (10 << CAN_MSGID_API_S))
//##### FIRST END #####
#define LM_API_SPD_SET_NO_ACK (LM_API_SPD | (11 << CAN_MSGID_API_S))
#define LM_API_SPD_SET_NO_ACK (LM_API_SPD | (11 << CAN_MSGID_API_S))
//*****************************************************************************
//
// The Stellaris Motor Control Voltage Compensation Control API definitions.
//
//*****************************************************************************
#define LM_API_VCOMP (CAN_MSGID_MFR_LM | CAN_MSGID_DTYPE_MOTOR | \
CAN_API_MC_VCOMP)
#define LM_API_VCOMP_EN (LM_API_VCOMP | (0 << CAN_MSGID_API_S))
#define LM_API_VCOMP_DIS (LM_API_VCOMP | (1 << CAN_MSGID_API_S))
#define LM_API_VCOMP_SET (LM_API_VCOMP | (2 << CAN_MSGID_API_S))
#define LM_API_VCOMP_IN_RAMP (LM_API_VCOMP | (3 << CAN_MSGID_API_S))
#define LM_API_VCOMP_COMP_RAMP (LM_API_VCOMP | (4 << CAN_MSGID_API_S))
#define LM_API_VCOMP \
(CAN_MSGID_MFR_LM | CAN_MSGID_DTYPE_MOTOR | CAN_API_MC_VCOMP)
#define LM_API_VCOMP_EN (LM_API_VCOMP | (0 << CAN_MSGID_API_S))
#define LM_API_VCOMP_DIS (LM_API_VCOMP | (1 << CAN_MSGID_API_S))
#define LM_API_VCOMP_SET (LM_API_VCOMP | (2 << CAN_MSGID_API_S))
#define LM_API_VCOMP_IN_RAMP (LM_API_VCOMP | (3 << CAN_MSGID_API_S))
#define LM_API_VCOMP_COMP_RAMP (LM_API_VCOMP | (4 << CAN_MSGID_API_S))
//##### FIRST BEGIN #####
#define LM_API_VCOMP_T_EN (LM_API_VCOMP | (5 << CAN_MSGID_API_S))
#define LM_API_VCOMP_T_SET (LM_API_VCOMP | (6 << CAN_MSGID_API_S))
#define LM_API_VCOMP_T_SET_NO_ACK \
(LM_API_VCOMP | (8 << CAN_MSGID_API_S))
#define LM_API_VCOMP_T_EN (LM_API_VCOMP | (5 << CAN_MSGID_API_S))
#define LM_API_VCOMP_T_SET (LM_API_VCOMP | (6 << CAN_MSGID_API_S))
#define LM_API_VCOMP_T_SET_NO_ACK (LM_API_VCOMP | (8 << CAN_MSGID_API_S))
//##### FIRST END #####
#define LM_API_VCOMP_SET_NO_ACK (LM_API_VCOMP | (9 << CAN_MSGID_API_S))
@@ -189,40 +186,38 @@
// The Stellaris Motor Class Position Control API definitions.
//
//*****************************************************************************
#define LM_API_POS (CAN_MSGID_MFR_LM | CAN_MSGID_DTYPE_MOTOR | \
CAN_API_MC_POS)
#define LM_API_POS_EN (LM_API_POS | (0 << CAN_MSGID_API_S))
#define LM_API_POS_DIS (LM_API_POS | (1 << CAN_MSGID_API_S))
#define LM_API_POS_SET (LM_API_POS | (2 << CAN_MSGID_API_S))
#define LM_API_POS_PC (LM_API_POS | (3 << CAN_MSGID_API_S))
#define LM_API_POS_IC (LM_API_POS | (4 << CAN_MSGID_API_S))
#define LM_API_POS_DC (LM_API_POS | (5 << CAN_MSGID_API_S))
#define LM_API_POS_REF (LM_API_POS | (6 << CAN_MSGID_API_S))
#define LM_API_POS (CAN_MSGID_MFR_LM | CAN_MSGID_DTYPE_MOTOR | CAN_API_MC_POS)
#define LM_API_POS_EN (LM_API_POS | (0 << CAN_MSGID_API_S))
#define LM_API_POS_DIS (LM_API_POS | (1 << CAN_MSGID_API_S))
#define LM_API_POS_SET (LM_API_POS | (2 << CAN_MSGID_API_S))
#define LM_API_POS_PC (LM_API_POS | (3 << CAN_MSGID_API_S))
#define LM_API_POS_IC (LM_API_POS | (4 << CAN_MSGID_API_S))
#define LM_API_POS_DC (LM_API_POS | (5 << CAN_MSGID_API_S))
#define LM_API_POS_REF (LM_API_POS | (6 << CAN_MSGID_API_S))
//##### FIRST BEGIN #####
#define LM_API_POS_T_EN (LM_API_POS | (7 << CAN_MSGID_API_S))
#define LM_API_POS_T_SET (LM_API_POS | (8 << CAN_MSGID_API_S))
#define LM_API_POS_T_EN (LM_API_POS | (7 << CAN_MSGID_API_S))
#define LM_API_POS_T_SET (LM_API_POS | (8 << CAN_MSGID_API_S))
#define LM_API_POS_T_SET_NO_ACK (LM_API_POS | (10 << CAN_MSGID_API_S))
//##### FIRST END #####
#define LM_API_POS_SET_NO_ACK (LM_API_POS | (11 << CAN_MSGID_API_S))
#define LM_API_POS_SET_NO_ACK (LM_API_POS | (11 << CAN_MSGID_API_S))
//*****************************************************************************
//
// The Stellaris Motor Class Current Control API definitions.
//
//*****************************************************************************
#define LM_API_ICTRL (CAN_MSGID_MFR_LM | CAN_MSGID_DTYPE_MOTOR | \
CAN_API_MC_ICTRL)
#define LM_API_ICTRL_EN (LM_API_ICTRL | (0 << CAN_MSGID_API_S))
#define LM_API_ICTRL_DIS (LM_API_ICTRL | (1 << CAN_MSGID_API_S))
#define LM_API_ICTRL_SET (LM_API_ICTRL | (2 << CAN_MSGID_API_S))
#define LM_API_ICTRL_PC (LM_API_ICTRL | (3 << CAN_MSGID_API_S))
#define LM_API_ICTRL_IC (LM_API_ICTRL | (4 << CAN_MSGID_API_S))
#define LM_API_ICTRL_DC (LM_API_ICTRL | (5 << CAN_MSGID_API_S))
#define LM_API_ICTRL \
(CAN_MSGID_MFR_LM | CAN_MSGID_DTYPE_MOTOR | CAN_API_MC_ICTRL)
#define LM_API_ICTRL_EN (LM_API_ICTRL | (0 << CAN_MSGID_API_S))
#define LM_API_ICTRL_DIS (LM_API_ICTRL | (1 << CAN_MSGID_API_S))
#define LM_API_ICTRL_SET (LM_API_ICTRL | (2 << CAN_MSGID_API_S))
#define LM_API_ICTRL_PC (LM_API_ICTRL | (3 << CAN_MSGID_API_S))
#define LM_API_ICTRL_IC (LM_API_ICTRL | (4 << CAN_MSGID_API_S))
#define LM_API_ICTRL_DC (LM_API_ICTRL | (5 << CAN_MSGID_API_S))
//##### FIRST BEGIN #####
#define LM_API_ICTRL_T_EN (LM_API_ICTRL | (6 << CAN_MSGID_API_S))
#define LM_API_ICTRL_T_SET (LM_API_ICTRL | (7 << CAN_MSGID_API_S))
#define LM_API_ICTRL_T_SET_NO_ACK \
(LM_API_ICTRL | (9 << CAN_MSGID_API_S))
#define LM_API_ICTRL_T_EN (LM_API_ICTRL | (6 << CAN_MSGID_API_S))
#define LM_API_ICTRL_T_SET (LM_API_ICTRL | (7 << CAN_MSGID_API_S))
#define LM_API_ICTRL_T_SET_NO_ACK (LM_API_ICTRL | (9 << CAN_MSGID_API_S))
//##### FIRST END #####
#define LM_API_ICTRL_SET_NO_ACK (LM_API_ICTRL | (10 << CAN_MSGID_API_S))
@@ -231,18 +226,18 @@
// The Stellaris Motor Class Firmware Update API definitions.
//
//*****************************************************************************
#define LM_API_UPD (CAN_MSGID_MFR_LM | CAN_MSGID_DTYPE_UPDATE)
#define LM_API_UPD_PING (LM_API_UPD | (0 << CAN_MSGID_API_S))
#define LM_API_UPD_DOWNLOAD (LM_API_UPD | (1 << CAN_MSGID_API_S))
#define LM_API_UPD_SEND_DATA (LM_API_UPD | (2 << CAN_MSGID_API_S))
#define LM_API_UPD_RESET (LM_API_UPD | (3 << CAN_MSGID_API_S))
#define LM_API_UPD_ACK (LM_API_UPD | (4 << CAN_MSGID_API_S))
#define LM_API_HWVER (LM_API_UPD | (5 << CAN_MSGID_API_S))
#define LM_API_UPD_REQUEST (LM_API_UPD | (6 << CAN_MSGID_API_S))
#define LM_API_UPD (CAN_MSGID_MFR_LM | CAN_MSGID_DTYPE_UPDATE)
#define LM_API_UPD_PING (LM_API_UPD | (0 << CAN_MSGID_API_S))
#define LM_API_UPD_DOWNLOAD (LM_API_UPD | (1 << CAN_MSGID_API_S))
#define LM_API_UPD_SEND_DATA (LM_API_UPD | (2 << CAN_MSGID_API_S))
#define LM_API_UPD_RESET (LM_API_UPD | (3 << CAN_MSGID_API_S))
#define LM_API_UPD_ACK (LM_API_UPD | (4 << CAN_MSGID_API_S))
#define LM_API_HWVER (LM_API_UPD | (5 << CAN_MSGID_API_S))
#define LM_API_UPD_REQUEST (LM_API_UPD | (6 << CAN_MSGID_API_S))
//##### FIRST BEGIN #####
#define LM_API_UNTRUST_EN (LM_API_UPD | (11 << CAN_MSGID_API_S))
#define LM_API_TRUST_EN (LM_API_UPD | (12 << CAN_MSGID_API_S))
#define LM_API_TRUST_HEARTBEAT (LM_API_UPD | (13 << CAN_MSGID_API_S))
#define LM_API_UNTRUST_EN (LM_API_UPD | (11 << CAN_MSGID_API_S))
#define LM_API_TRUST_EN (LM_API_UPD | (12 << CAN_MSGID_API_S))
#define LM_API_TRUST_HEARTBEAT (LM_API_UPD | (13 << CAN_MSGID_API_S))
//##### FIRST END #####
//*****************************************************************************
@@ -250,20 +245,20 @@
// The Stellaris Motor Class Status API definitions.
//
//*****************************************************************************
#define LM_API_STATUS (CAN_MSGID_MFR_LM | CAN_MSGID_DTYPE_MOTOR | \
CAN_API_MC_STATUS)
#define LM_API_STATUS_VOLTOUT (LM_API_STATUS | (0 << CAN_MSGID_API_S))
#define LM_API_STATUS_VOLTBUS (LM_API_STATUS | (1 << CAN_MSGID_API_S))
#define LM_API_STATUS_CURRENT (LM_API_STATUS | (2 << CAN_MSGID_API_S))
#define LM_API_STATUS_TEMP (LM_API_STATUS | (3 << CAN_MSGID_API_S))
#define LM_API_STATUS_POS (LM_API_STATUS | (4 << CAN_MSGID_API_S))
#define LM_API_STATUS_SPD (LM_API_STATUS | (5 << CAN_MSGID_API_S))
#define LM_API_STATUS_LIMIT (LM_API_STATUS | (6 << CAN_MSGID_API_S))
#define LM_API_STATUS_FAULT (LM_API_STATUS | (7 << CAN_MSGID_API_S))
#define LM_API_STATUS_POWER (LM_API_STATUS | (8 << CAN_MSGID_API_S))
#define LM_API_STATUS_CMODE (LM_API_STATUS | (9 << CAN_MSGID_API_S))
#define LM_API_STATUS_VOUT (LM_API_STATUS | (10 << CAN_MSGID_API_S))
#define LM_API_STATUS_STKY_FLT (LM_API_STATUS | (11 << CAN_MSGID_API_S))
#define LM_API_STATUS \
(CAN_MSGID_MFR_LM | CAN_MSGID_DTYPE_MOTOR | CAN_API_MC_STATUS)
#define LM_API_STATUS_VOLTOUT (LM_API_STATUS | (0 << CAN_MSGID_API_S))
#define LM_API_STATUS_VOLTBUS (LM_API_STATUS | (1 << CAN_MSGID_API_S))
#define LM_API_STATUS_CURRENT (LM_API_STATUS | (2 << CAN_MSGID_API_S))
#define LM_API_STATUS_TEMP (LM_API_STATUS | (3 << CAN_MSGID_API_S))
#define LM_API_STATUS_POS (LM_API_STATUS | (4 << CAN_MSGID_API_S))
#define LM_API_STATUS_SPD (LM_API_STATUS | (5 << CAN_MSGID_API_S))
#define LM_API_STATUS_LIMIT (LM_API_STATUS | (6 << CAN_MSGID_API_S))
#define LM_API_STATUS_FAULT (LM_API_STATUS | (7 << CAN_MSGID_API_S))
#define LM_API_STATUS_POWER (LM_API_STATUS | (8 << CAN_MSGID_API_S))
#define LM_API_STATUS_CMODE (LM_API_STATUS | (9 << CAN_MSGID_API_S))
#define LM_API_STATUS_VOUT (LM_API_STATUS | (10 << CAN_MSGID_API_S))
#define LM_API_STATUS_STKY_FLT (LM_API_STATUS | (11 << CAN_MSGID_API_S))
#define LM_API_STATUS_FLT_COUNT (LM_API_STATUS | (12 << CAN_MSGID_API_S))
//*****************************************************************************
@@ -272,72 +267,66 @@
// the status request for LM_API_STATUS_LIMIT.
//
//*****************************************************************************
#define LM_STATUS_LIMIT_FWD 0x01
#define LM_STATUS_LIMIT_REV 0x02
#define LM_STATUS_LIMIT_SFWD 0x04
#define LM_STATUS_LIMIT_SREV 0x08
#define LM_STATUS_LIMIT_STKY_FWD \
0x10
#define LM_STATUS_LIMIT_STKY_REV \
0x20
#define LM_STATUS_LIMIT_STKY_SFWD \
0x40
#define LM_STATUS_LIMIT_STKY_SREV \
0x80
#define LM_STATUS_LIMIT_FWD 0x01
#define LM_STATUS_LIMIT_REV 0x02
#define LM_STATUS_LIMIT_SFWD 0x04
#define LM_STATUS_LIMIT_SREV 0x08
#define LM_STATUS_LIMIT_STKY_FWD 0x10
#define LM_STATUS_LIMIT_STKY_REV 0x20
#define LM_STATUS_LIMIT_STKY_SFWD 0x40
#define LM_STATUS_LIMIT_STKY_SREV 0x80
//*****************************************************************************
//
// LM Motor Control status codes returned due to the CAN_STATUS_CODE_M field.
//
//*****************************************************************************
#define LM_STATUS_FAULT_ILIMIT 0x01
#define LM_STATUS_FAULT_TLIMIT 0x02
#define LM_STATUS_FAULT_VLIMIT 0x04
#define LM_STATUS_FAULT_ILIMIT 0x01
#define LM_STATUS_FAULT_TLIMIT 0x02
#define LM_STATUS_FAULT_VLIMIT 0x04
//*****************************************************************************
//
// The Stellaris Motor Class Configuration API definitions.
//
//*****************************************************************************
#define LM_API_CFG (CAN_MSGID_MFR_LM | CAN_MSGID_DTYPE_MOTOR | \
CAN_API_MC_CFG)
#define LM_API_CFG_NUM_BRUSHES (LM_API_CFG | (0 << CAN_MSGID_API_S))
#define LM_API_CFG_ENC_LINES (LM_API_CFG | (1 << CAN_MSGID_API_S))
#define LM_API_CFG_POT_TURNS (LM_API_CFG | (2 << CAN_MSGID_API_S))
#define LM_API_CFG_BRAKE_COAST (LM_API_CFG | (3 << CAN_MSGID_API_S))
#define LM_API_CFG_LIMIT_MODE (LM_API_CFG | (4 << CAN_MSGID_API_S))
#define LM_API_CFG_LIMIT_FWD (LM_API_CFG | (5 << CAN_MSGID_API_S))
#define LM_API_CFG_LIMIT_REV (LM_API_CFG | (6 << CAN_MSGID_API_S))
#define LM_API_CFG_MAX_VOUT (LM_API_CFG | (7 << CAN_MSGID_API_S))
#define LM_API_CFG_FAULT_TIME (LM_API_CFG | (8 << CAN_MSGID_API_S))
#define LM_API_CFG (CAN_MSGID_MFR_LM | CAN_MSGID_DTYPE_MOTOR | CAN_API_MC_CFG)
#define LM_API_CFG_NUM_BRUSHES (LM_API_CFG | (0 << CAN_MSGID_API_S))
#define LM_API_CFG_ENC_LINES (LM_API_CFG | (1 << CAN_MSGID_API_S))
#define LM_API_CFG_POT_TURNS (LM_API_CFG | (2 << CAN_MSGID_API_S))
#define LM_API_CFG_BRAKE_COAST (LM_API_CFG | (3 << CAN_MSGID_API_S))
#define LM_API_CFG_LIMIT_MODE (LM_API_CFG | (4 << CAN_MSGID_API_S))
#define LM_API_CFG_LIMIT_FWD (LM_API_CFG | (5 << CAN_MSGID_API_S))
#define LM_API_CFG_LIMIT_REV (LM_API_CFG | (6 << CAN_MSGID_API_S))
#define LM_API_CFG_MAX_VOUT (LM_API_CFG | (7 << CAN_MSGID_API_S))
#define LM_API_CFG_FAULT_TIME (LM_API_CFG | (8 << CAN_MSGID_API_S))
//*****************************************************************************
//
// The Stellaris ACK API definition.
//
//*****************************************************************************
#define LM_API_ACK (CAN_MSGID_MFR_LM | CAN_MSGID_DTYPE_MOTOR | \
CAN_API_MC_ACK)
#define LM_API_ACK (CAN_MSGID_MFR_LM | CAN_MSGID_DTYPE_MOTOR | CAN_API_MC_ACK)
//*****************************************************************************
//
// The 8 bit values that can be returned by a call to LM_API_STATUS_HWVER.
//
//*****************************************************************************
#define LM_HWVER_UNKNOWN 0x00
#define LM_HWVER_JAG_1_0 0x01
#define LM_HWVER_JAG_2_0 0x02
#define LM_HWVER_UNKNOWN 0x00
#define LM_HWVER_JAG_1_0 0x01
#define LM_HWVER_JAG_2_0 0x02
//*****************************************************************************
//
// The 8 bit values that can be returned by a call to LM_API_STATUS_CMODE.
//
//*****************************************************************************
#define LM_STATUS_CMODE_VOLT 0x00
#define LM_STATUS_CMODE_VOLT 0x00
#define LM_STATUS_CMODE_CURRENT 0x01
#define LM_STATUS_CMODE_SPEED 0x02
#define LM_STATUS_CMODE_POS 0x03
#define LM_STATUS_CMODE_VCOMP 0x04
#define LM_STATUS_CMODE_SPEED 0x02
#define LM_STATUS_CMODE_POS 0x03
#define LM_STATUS_CMODE_VCOMP 0x04
//*****************************************************************************
//
@@ -346,42 +335,42 @@
// none will be selected.
//
//*****************************************************************************
#define LM_REF_ENCODER 0x00
#define LM_REF_POT 0x01
#define LM_REF_INV_ENCODER 0x02
#define LM_REF_QUAD_ENCODER 0x03
#define LM_REF_NONE 0xff
#define LM_REF_ENCODER 0x00
#define LM_REF_POT 0x01
#define LM_REF_INV_ENCODER 0x02
#define LM_REF_QUAD_ENCODER 0x03
#define LM_REF_NONE 0xff
//*****************************************************************************
//
// The flags that are used to indicate the currently active fault sources.
//
//*****************************************************************************
#define LM_FAULT_CURRENT 0x01
#define LM_FAULT_TEMP 0x02
#define LM_FAULT_VBUS 0x04
#define LM_FAULT_GATE_DRIVE 0x08
#define LM_FAULT_COMM 0x10
#define LM_FAULT_CURRENT 0x01
#define LM_FAULT_TEMP 0x02
#define LM_FAULT_VBUS 0x04
#define LM_FAULT_GATE_DRIVE 0x08
#define LM_FAULT_COMM 0x10
//*****************************************************************************
//
// The Stellaris Motor Class Periodic Status API definitions.
//
//*****************************************************************************
#define LM_API_PSTAT (CAN_MSGID_MFR_LM | CAN_MSGID_DTYPE_MOTOR | \
CAN_API_MC_PSTAT)
#define LM_API_PSTAT_PER_EN_S0 (LM_API_PSTAT | (0 << CAN_MSGID_API_S))
#define LM_API_PSTAT_PER_EN_S1 (LM_API_PSTAT | (1 << CAN_MSGID_API_S))
#define LM_API_PSTAT_PER_EN_S2 (LM_API_PSTAT | (2 << CAN_MSGID_API_S))
#define LM_API_PSTAT_PER_EN_S3 (LM_API_PSTAT | (3 << CAN_MSGID_API_S))
#define LM_API_PSTAT_CFG_S0 (LM_API_PSTAT | (4 << CAN_MSGID_API_S))
#define LM_API_PSTAT_CFG_S1 (LM_API_PSTAT | (5 << CAN_MSGID_API_S))
#define LM_API_PSTAT_CFG_S2 (LM_API_PSTAT | (6 << CAN_MSGID_API_S))
#define LM_API_PSTAT_CFG_S3 (LM_API_PSTAT | (7 << CAN_MSGID_API_S))
#define LM_API_PSTAT_DATA_S0 (LM_API_PSTAT | (8 << CAN_MSGID_API_S))
#define LM_API_PSTAT_DATA_S1 (LM_API_PSTAT | (9 << CAN_MSGID_API_S))
#define LM_API_PSTAT_DATA_S2 (LM_API_PSTAT | (10 << CAN_MSGID_API_S))
#define LM_API_PSTAT_DATA_S3 (LM_API_PSTAT | (11 << CAN_MSGID_API_S))
#define LM_API_PSTAT \
(CAN_MSGID_MFR_LM | CAN_MSGID_DTYPE_MOTOR | CAN_API_MC_PSTAT)
#define LM_API_PSTAT_PER_EN_S0 (LM_API_PSTAT | (0 << CAN_MSGID_API_S))
#define LM_API_PSTAT_PER_EN_S1 (LM_API_PSTAT | (1 << CAN_MSGID_API_S))
#define LM_API_PSTAT_PER_EN_S2 (LM_API_PSTAT | (2 << CAN_MSGID_API_S))
#define LM_API_PSTAT_PER_EN_S3 (LM_API_PSTAT | (3 << CAN_MSGID_API_S))
#define LM_API_PSTAT_CFG_S0 (LM_API_PSTAT | (4 << CAN_MSGID_API_S))
#define LM_API_PSTAT_CFG_S1 (LM_API_PSTAT | (5 << CAN_MSGID_API_S))
#define LM_API_PSTAT_CFG_S2 (LM_API_PSTAT | (6 << CAN_MSGID_API_S))
#define LM_API_PSTAT_CFG_S3 (LM_API_PSTAT | (7 << CAN_MSGID_API_S))
#define LM_API_PSTAT_DATA_S0 (LM_API_PSTAT | (8 << CAN_MSGID_API_S))
#define LM_API_PSTAT_DATA_S1 (LM_API_PSTAT | (9 << CAN_MSGID_API_S))
#define LM_API_PSTAT_DATA_S2 (LM_API_PSTAT | (10 << CAN_MSGID_API_S))
#define LM_API_PSTAT_DATA_S3 (LM_API_PSTAT | (11 << CAN_MSGID_API_S))
//*****************************************************************************
//
@@ -390,39 +379,37 @@
// little-endian, therefore B0 is the least significant byte.
//
//*****************************************************************************
#define LM_PSTAT_END 0
#define LM_PSTAT_VOLTOUT_B0 1
#define LM_PSTAT_VOLTOUT_B1 2
#define LM_PSTAT_VOLTBUS_B0 3
#define LM_PSTAT_VOLTBUS_B1 4
#define LM_PSTAT_CURRENT_B0 5
#define LM_PSTAT_CURRENT_B1 6
#define LM_PSTAT_TEMP_B0 7
#define LM_PSTAT_TEMP_B1 8
#define LM_PSTAT_POS_B0 9
#define LM_PSTAT_POS_B1 10
#define LM_PSTAT_POS_B2 11
#define LM_PSTAT_POS_B3 12
#define LM_PSTAT_SPD_B0 13
#define LM_PSTAT_SPD_B1 14
#define LM_PSTAT_SPD_B2 15
#define LM_PSTAT_SPD_B3 16
#define LM_PSTAT_LIMIT_NCLR 17
#define LM_PSTAT_LIMIT_CLR 18
#define LM_PSTAT_FAULT 19
#define LM_PSTAT_STKY_FLT_NCLR 20
#define LM_PSTAT_STKY_FLT_CLR 21
#define LM_PSTAT_VOUT_B0 22
#define LM_PSTAT_VOUT_B1 23
#define LM_PSTAT_FLT_COUNT_CURRENT \
24
#define LM_PSTAT_END 0
#define LM_PSTAT_VOLTOUT_B0 1
#define LM_PSTAT_VOLTOUT_B1 2
#define LM_PSTAT_VOLTBUS_B0 3
#define LM_PSTAT_VOLTBUS_B1 4
#define LM_PSTAT_CURRENT_B0 5
#define LM_PSTAT_CURRENT_B1 6
#define LM_PSTAT_TEMP_B0 7
#define LM_PSTAT_TEMP_B1 8
#define LM_PSTAT_POS_B0 9
#define LM_PSTAT_POS_B1 10
#define LM_PSTAT_POS_B2 11
#define LM_PSTAT_POS_B3 12
#define LM_PSTAT_SPD_B0 13
#define LM_PSTAT_SPD_B1 14
#define LM_PSTAT_SPD_B2 15
#define LM_PSTAT_SPD_B3 16
#define LM_PSTAT_LIMIT_NCLR 17
#define LM_PSTAT_LIMIT_CLR 18
#define LM_PSTAT_FAULT 19
#define LM_PSTAT_STKY_FLT_NCLR 20
#define LM_PSTAT_STKY_FLT_CLR 21
#define LM_PSTAT_VOUT_B0 22
#define LM_PSTAT_VOUT_B1 23
#define LM_PSTAT_FLT_COUNT_CURRENT 24
#define LM_PSTAT_FLT_COUNT_TEMP 25
#define LM_PSTAT_FLT_COUNT_VOLTBUS \
26
#define LM_PSTAT_FLT_COUNT_VOLTBUS 26
#define LM_PSTAT_FLT_COUNT_GATE 27
#define LM_PSTAT_FLT_COUNT_COMM 28
#define LM_PSTAT_CANSTS 29
#define LM_PSTAT_CANERR_B0 30
#define LM_PSTAT_CANERR_B1 31
#define LM_PSTAT_CANSTS 29
#define LM_PSTAT_CANERR_B0 30
#define LM_PSTAT_CANERR_B1 31
#endif // __CAN_PROTO_H__
#endif // __CAN_PROTO_H__

View File

@@ -25,206 +25,222 @@
* Luminary Micro / Vex Robotics Jaguar Speed Control
*/
class CANJaguar : public MotorSafety,
public CANSpeedController,
public ErrorBase,
public LiveWindowSendable,
public ITableListener
{
public:
// The internal PID control loop in the Jaguar runs at 1kHz.
static const int32_t kControllerRate = 1000;
static constexpr double kApproxBusVoltage = 12.0;
public CANSpeedController,
public ErrorBase,
public LiveWindowSendable,
public ITableListener {
public:
// The internal PID control loop in the Jaguar runs at 1kHz.
static const int32_t kControllerRate = 1000;
static constexpr double kApproxBusVoltage = 12.0;
// Control mode tags
/** Sets an encoder as the speed reference only. <br> Passed as the "tag" when setting the control mode.*/
static const struct EncoderStruct {} Encoder;
/** Sets a quadrature encoder as the position and speed reference. <br> Passed as the "tag" when setting the control mode.*/
static const struct QuadEncoderStruct {} QuadEncoder;
/** Sets a potentiometer as the position reference only. <br> Passed as the "tag" when setting the control mode. */
static const struct PotentiometerStruct {} Potentiometer;
// Control mode tags
/** Sets an encoder as the speed reference only. <br> Passed as the "tag" when
* setting the control mode.*/
static const struct EncoderStruct {
} Encoder;
/** Sets a quadrature encoder as the position and speed reference. <br> Passed
* as the "tag" when setting the control mode.*/
static const struct QuadEncoderStruct {
} QuadEncoder;
/** Sets a potentiometer as the position reference only. <br> Passed as the
* "tag" when setting the control mode. */
static const struct PotentiometerStruct {
} Potentiometer;
explicit CANJaguar(uint8_t deviceNumber);
virtual ~CANJaguar();
explicit CANJaguar(uint8_t deviceNumber);
virtual ~CANJaguar();
uint8_t getDeviceNumber() const;
uint8_t GetHardwareVersion() const;
uint8_t getDeviceNumber() const;
uint8_t GetHardwareVersion() const;
// PIDOutput interface
virtual void PIDWrite(float output) override;
// PIDOutput interface
virtual void PIDWrite(float output) override;
// Control mode methods
void EnableControl(double encoderInitialPosition = 0.0);
void DisableControl();
// Control mode methods
void EnableControl(double encoderInitialPosition = 0.0);
void DisableControl();
void SetPercentMode();
void SetPercentMode(EncoderStruct, uint16_t codesPerRev);
void SetPercentMode(QuadEncoderStruct, uint16_t codesPerRev);
void SetPercentMode(PotentiometerStruct);
void SetPercentMode();
void SetPercentMode(EncoderStruct, uint16_t codesPerRev);
void SetPercentMode(QuadEncoderStruct, uint16_t codesPerRev);
void SetPercentMode(PotentiometerStruct);
void SetCurrentMode(double p, double i, double d);
void SetCurrentMode(EncoderStruct, uint16_t codesPerRev, double p, double i, double d);
void SetCurrentMode(QuadEncoderStruct, uint16_t codesPerRev, double p, double i, double d);
void SetCurrentMode(PotentiometerStruct, double p, double i, double d);
void SetCurrentMode(double p, double i, double d);
void SetCurrentMode(EncoderStruct, uint16_t codesPerRev, double p, double i,
double d);
void SetCurrentMode(QuadEncoderStruct, uint16_t codesPerRev, double p,
double i, double d);
void SetCurrentMode(PotentiometerStruct, double p, double i, double d);
void SetSpeedMode(EncoderStruct, uint16_t codesPerRev, double p, double i, double d);
void SetSpeedMode(QuadEncoderStruct, uint16_t codesPerRev, double p, double i, double d);
void SetSpeedMode(EncoderStruct, uint16_t codesPerRev, double p, double i,
double d);
void SetSpeedMode(QuadEncoderStruct, uint16_t codesPerRev, double p, double i,
double d);
void SetPositionMode(QuadEncoderStruct, uint16_t codesPerRev, double p, double i, double d);
void SetPositionMode(PotentiometerStruct, double p, double i, double d);
void SetPositionMode(QuadEncoderStruct, uint16_t codesPerRev, double p,
double i, double d);
void SetPositionMode(PotentiometerStruct, double p, double i, double d);
void SetVoltageMode();
void SetVoltageMode(EncoderStruct, uint16_t codesPerRev);
void SetVoltageMode(QuadEncoderStruct, uint16_t codesPerRev);
void SetVoltageMode(PotentiometerStruct);
void SetVoltageMode();
void SetVoltageMode(EncoderStruct, uint16_t codesPerRev);
void SetVoltageMode(QuadEncoderStruct, uint16_t codesPerRev);
void SetVoltageMode(PotentiometerStruct);
// CANSpeedController interface
virtual float Get() const override;
virtual void Set(float value, uint8_t syncGroup=0) override;
virtual void Disable() override;
virtual void SetP(double p) override;
virtual void SetI(double i) override;
virtual void SetD(double d) override;
virtual void SetPID(double p, double i, double d) override;
virtual double GetP() const override;
virtual double GetI() const override;
virtual double GetD() const override;
virtual float GetBusVoltage() const override;
virtual float GetOutputVoltage() const override;
virtual float GetOutputCurrent() const override;
virtual float GetTemperature() const override;
virtual double GetPosition() const override;
virtual double GetSpeed() const override;
virtual bool GetForwardLimitOK() const override;
virtual bool GetReverseLimitOK() const override;
virtual uint16_t GetFaults() const override;
virtual void SetVoltageRampRate(double rampRate) override;
virtual uint32_t GetFirmwareVersion() const override;
virtual void ConfigNeutralMode(NeutralMode mode) override;
virtual void ConfigEncoderCodesPerRev(uint16_t codesPerRev) override;
virtual void ConfigPotentiometerTurns(uint16_t turns) override;
virtual void ConfigSoftPositionLimits(double forwardLimitPosition, double reverseLimitPosition) override;
virtual void DisableSoftPositionLimits() override;
virtual void ConfigLimitMode(LimitMode mode) override;
virtual void ConfigForwardLimit(double forwardLimitPosition) override;
virtual void ConfigReverseLimit(double reverseLimitPosition) override;
virtual void ConfigMaxOutputVoltage(double voltage) override;
virtual void ConfigFaultTime(float faultTime) override;
virtual void SetControlMode(ControlMode mode);
virtual ControlMode GetControlMode() const;
// CANSpeedController interface
virtual float Get() const override;
virtual void Set(float value, uint8_t syncGroup = 0) override;
virtual void Disable() override;
virtual void SetP(double p) override;
virtual void SetI(double i) override;
virtual void SetD(double d) override;
virtual void SetPID(double p, double i, double d) override;
virtual double GetP() const override;
virtual double GetI() const override;
virtual double GetD() const override;
virtual float GetBusVoltage() const override;
virtual float GetOutputVoltage() const override;
virtual float GetOutputCurrent() const override;
virtual float GetTemperature() const override;
virtual double GetPosition() const override;
virtual double GetSpeed() const override;
virtual bool GetForwardLimitOK() const override;
virtual bool GetReverseLimitOK() const override;
virtual uint16_t GetFaults() const override;
virtual void SetVoltageRampRate(double rampRate) override;
virtual uint32_t GetFirmwareVersion() const override;
virtual void ConfigNeutralMode(NeutralMode mode) override;
virtual void ConfigEncoderCodesPerRev(uint16_t codesPerRev) override;
virtual void ConfigPotentiometerTurns(uint16_t turns) override;
virtual void ConfigSoftPositionLimits(double forwardLimitPosition,
double reverseLimitPosition) override;
virtual void DisableSoftPositionLimits() override;
virtual void ConfigLimitMode(LimitMode mode) override;
virtual void ConfigForwardLimit(double forwardLimitPosition) override;
virtual void ConfigReverseLimit(double reverseLimitPosition) override;
virtual void ConfigMaxOutputVoltage(double voltage) override;
virtual void ConfigFaultTime(float faultTime) override;
virtual void SetControlMode(ControlMode mode);
virtual ControlMode GetControlMode() const;
static void UpdateSyncGroup(uint8_t syncGroup);
static void UpdateSyncGroup(uint8_t syncGroup);
void SetExpiration(float timeout) override;
float GetExpiration() const override;
bool IsAlive() const override;
void StopMotor() override;
bool IsSafetyEnabled() const override;
void SetSafetyEnabled(bool enabled) override;
void GetDescription(char *desc) const override;
uint8_t GetDeviceID() const;
void SetExpiration(float timeout) override;
float GetExpiration() const override;
bool IsAlive() const override;
void StopMotor() override;
bool IsSafetyEnabled() const override;
void SetSafetyEnabled(bool enabled) override;
void GetDescription(char *desc) const override;
uint8_t GetDeviceID() const;
//SpeedController overrides
// SpeedController overrides
virtual void SetInverted(bool isInverted) override;
virtual bool GetInverted() const override;
protected:
// Control mode helpers
void SetSpeedReference(uint8_t reference);
uint8_t GetSpeedReference() const;
virtual bool GetInverted() const override;
void SetPositionReference(uint8_t reference);
uint8_t GetPositionReference() const;
protected:
// Control mode helpers
void SetSpeedReference(uint8_t reference);
uint8_t GetSpeedReference() const;
uint8_t packPercentage(uint8_t *buffer, double value);
uint8_t packFXP8_8(uint8_t *buffer, double value);
uint8_t packFXP16_16(uint8_t *buffer, double value);
uint8_t packint16_t(uint8_t *buffer, int16_t value);
uint8_t packint32_t(uint8_t *buffer, int32_t value);
double unpackPercentage(uint8_t *buffer) const;
double unpackFXP8_8(uint8_t *buffer) const;
double unpackFXP16_16(uint8_t *buffer) const;
int16_t unpackint16_t(uint8_t *buffer) const;
int32_t unpackint32_t(uint8_t *buffer) const;
void SetPositionReference(uint8_t reference);
uint8_t GetPositionReference() const;
void sendMessage(uint32_t messageID, const uint8_t *data, uint8_t dataSize, int32_t period = CAN_SEND_PERIOD_NO_REPEAT);
void requestMessage(uint32_t messageID, int32_t period = CAN_SEND_PERIOD_NO_REPEAT);
bool getMessage(uint32_t messageID, uint32_t mask, uint8_t *data, uint8_t *dataSize) const;
uint8_t packPercentage(uint8_t *buffer, double value);
uint8_t packFXP8_8(uint8_t *buffer, double value);
uint8_t packFXP16_16(uint8_t *buffer, double value);
uint8_t packint16_t(uint8_t *buffer, int16_t value);
uint8_t packint32_t(uint8_t *buffer, int32_t value);
double unpackPercentage(uint8_t *buffer) const;
double unpackFXP8_8(uint8_t *buffer) const;
double unpackFXP16_16(uint8_t *buffer) const;
int16_t unpackint16_t(uint8_t *buffer) const;
int32_t unpackint32_t(uint8_t *buffer) const;
void setupPeriodicStatus();
void updatePeriodicStatus() const;
void sendMessage(uint32_t messageID, const uint8_t *data, uint8_t dataSize,
int32_t period = CAN_SEND_PERIOD_NO_REPEAT);
void requestMessage(uint32_t messageID,
int32_t period = CAN_SEND_PERIOD_NO_REPEAT);
bool getMessage(uint32_t messageID, uint32_t mask, uint8_t *data,
uint8_t *dataSize) const;
mutable std::recursive_mutex m_mutex;
void setupPeriodicStatus();
void updatePeriodicStatus() const;
uint8_t m_deviceNumber;
float m_value;
mutable std::recursive_mutex m_mutex;
// Parameters/configuration
ControlMode m_controlMode;
uint8_t m_speedReference;
uint8_t m_positionReference;
double m_p;
double m_i;
double m_d;
NeutralMode m_neutralMode;
uint16_t m_encoderCodesPerRev;
uint16_t m_potentiometerTurns;
LimitMode m_limitMode;
double m_forwardLimit;
double m_reverseLimit;
double m_maxOutputVoltage;
double m_voltageRampRate;
float m_faultTime;
uint8_t m_deviceNumber;
float m_value;
// Which parameters have been verified since they were last set?
bool m_controlModeVerified;
bool m_speedRefVerified;
bool m_posRefVerified;
bool m_pVerified;
bool m_iVerified;
bool m_dVerified;
bool m_neutralModeVerified;
bool m_encoderCodesPerRevVerified;
bool m_potentiometerTurnsVerified;
bool m_forwardLimitVerified;
bool m_reverseLimitVerified;
bool m_limitModeVerified;
bool m_maxOutputVoltageVerified;
bool m_voltageRampRateVerified;
bool m_faultTimeVerified;
// Parameters/configuration
ControlMode m_controlMode;
uint8_t m_speedReference;
uint8_t m_positionReference;
double m_p;
double m_i;
double m_d;
NeutralMode m_neutralMode;
uint16_t m_encoderCodesPerRev;
uint16_t m_potentiometerTurns;
LimitMode m_limitMode;
double m_forwardLimit;
double m_reverseLimit;
double m_maxOutputVoltage;
double m_voltageRampRate;
float m_faultTime;
// Status data
mutable float m_busVoltage;
mutable float m_outputVoltage;
mutable float m_outputCurrent;
mutable float m_temperature;
mutable double m_position;
mutable double m_speed;
mutable uint8_t m_limits;
mutable uint16_t m_faults;
uint32_t m_firmwareVersion;
uint8_t m_hardwareVersion;
// Which parameters have been verified since they were last set?
bool m_controlModeVerified;
bool m_speedRefVerified;
bool m_posRefVerified;
bool m_pVerified;
bool m_iVerified;
bool m_dVerified;
bool m_neutralModeVerified;
bool m_encoderCodesPerRevVerified;
bool m_potentiometerTurnsVerified;
bool m_forwardLimitVerified;
bool m_reverseLimitVerified;
bool m_limitModeVerified;
bool m_maxOutputVoltageVerified;
bool m_voltageRampRateVerified;
bool m_faultTimeVerified;
// Which periodic status messages have we received at least once?
mutable std::atomic<bool> m_receivedStatusMessage0;
mutable std::atomic<bool> m_receivedStatusMessage1;
mutable std::atomic<bool> m_receivedStatusMessage2;
// Status data
mutable float m_busVoltage;
mutable float m_outputVoltage;
mutable float m_outputCurrent;
mutable float m_temperature;
mutable double m_position;
mutable double m_speed;
mutable uint8_t m_limits;
mutable uint16_t m_faults;
uint32_t m_firmwareVersion;
uint8_t m_hardwareVersion;
bool m_controlEnabled;
// Which periodic status messages have we received at least once?
mutable std::atomic<bool> m_receivedStatusMessage0;
mutable std::atomic<bool> m_receivedStatusMessage1;
mutable std::atomic<bool> m_receivedStatusMessage2;
void verify();
bool m_controlEnabled;
MotorSafetyHelper *m_safetyHelper;
void verify();
void ValueChanged(ITable* source, const std::string& key, EntryValue value, bool isNew) override;
void UpdateTable() override;
void StartLiveWindowMode() override;
void StopLiveWindowMode() override;
std::string GetSmartDashboardType() const override;
void InitTable(ITable *subTable) override;
ITable * GetTable() const override;
MotorSafetyHelper *m_safetyHelper;
ITable *m_table;
void ValueChanged(ITable *source, const std::string &key, EntryValue value,
bool isNew) override;
void UpdateTable() override;
void StartLiveWindowMode() override;
void StopLiveWindowMode() override;
std::string GetSmartDashboardType() const override;
void InitTable(ITable *subTable) override;
ITable *GetTable() const override;
private:
void InitCANJaguar();
bool m_isInverted;
ITable *m_table;
private:
void InitCANJaguar();
bool m_isInverted;
};

View File

@@ -12,86 +12,84 @@
* @see CANJaguar
* @see CANTalon
*/
class CANSpeedController : public SpeedController
{
public:
enum ControlMode {
kPercentVbus=0,
kCurrent=1,
kSpeed=2,
kPosition=3,
kVoltage=4,
kFollower=5 // Not supported in Jaguar.
};
class CANSpeedController : public SpeedController {
public:
enum ControlMode {
kPercentVbus = 0,
kCurrent = 1,
kSpeed = 2,
kPosition = 3,
kVoltage = 4,
kFollower = 5 // Not supported in Jaguar.
};
enum Faults {
kCurrentFault = 1,
kTemperatureFault = 2,
kBusVoltageFault = 4,
kGateDriverFault = 8,
/* SRX extensions */
kFwdLimitSwitch = 0x10,
kRevLimitSwitch = 0x20,
kFwdSoftLimit = 0x40,
kRevSoftLimit = 0x80,
};
enum Faults {
kCurrentFault = 1,
kTemperatureFault = 2,
kBusVoltageFault = 4,
kGateDriverFault = 8,
/* SRX extensions */
kFwdLimitSwitch = 0x10,
kRevLimitSwitch = 0x20,
kFwdSoftLimit = 0x40,
kRevSoftLimit = 0x80,
};
enum Limits {
kForwardLimit = 1,
kReverseLimit = 2
};
enum Limits { kForwardLimit = 1, kReverseLimit = 2 };
enum NeutralMode {
/** Use the NeutralMode that is set by the jumper wire on the CAN device */
kNeutralMode_Jumper = 0,
/** Stop the motor's rotation by applying a force. */
kNeutralMode_Brake = 1,
/** Do not attempt to stop the motor. Instead allow it to coast to a stop without applying resistance. */
kNeutralMode_Coast = 2
};
enum NeutralMode {
/** Use the NeutralMode that is set by the jumper wire on the CAN device */
kNeutralMode_Jumper = 0,
/** Stop the motor's rotation by applying a force. */
kNeutralMode_Brake = 1,
/** Do not attempt to stop the motor. Instead allow it to coast to a stop
without applying resistance. */
kNeutralMode_Coast = 2
};
enum LimitMode {
/** Only use switches for limits */
kLimitMode_SwitchInputsOnly = 0,
/** Use both switches and soft limits */
kLimitMode_SoftPositionLimits = 1,
/* SRX extensions */
/** Disable switches and disable soft limits */
kLimitMode_SrxDisableSwitchInputs = 2,
};
enum LimitMode {
/** Only use switches for limits */
kLimitMode_SwitchInputsOnly = 0,
/** Use both switches and soft limits */
kLimitMode_SoftPositionLimits = 1,
/* SRX extensions */
/** Disable switches and disable soft limits */
kLimitMode_SrxDisableSwitchInputs = 2,
};
virtual float Get() const = 0;
virtual void Set(float value, uint8_t syncGroup=0) = 0;
virtual void Disable() = 0;
virtual void SetP(double p) = 0;
virtual void SetI(double i) = 0;
virtual void SetD(double d) = 0;
virtual void SetPID(double p, double i, double d) = 0;
virtual double GetP() const = 0;
virtual double GetI() const = 0;
virtual double GetD() const = 0;
virtual float GetBusVoltage() const = 0;
virtual float GetOutputVoltage() const = 0;
virtual float GetOutputCurrent() const = 0;
virtual float GetTemperature() const = 0;
virtual double GetPosition() const = 0;
virtual double GetSpeed() const = 0;
virtual bool GetForwardLimitOK() const = 0;
virtual bool GetReverseLimitOK() const = 0;
virtual uint16_t GetFaults() const = 0;
virtual void SetVoltageRampRate(double rampRate) = 0;
virtual uint32_t GetFirmwareVersion() const = 0;
virtual void ConfigNeutralMode(NeutralMode mode) = 0;
virtual void ConfigEncoderCodesPerRev(uint16_t codesPerRev) = 0;
virtual void ConfigPotentiometerTurns(uint16_t turns) = 0;
virtual void ConfigSoftPositionLimits(double forwardLimitPosition, double reverseLimitPosition) = 0;
virtual void DisableSoftPositionLimits() = 0;
virtual void ConfigLimitMode(LimitMode mode) = 0;
virtual void ConfigForwardLimit(double forwardLimitPosition) = 0;
virtual void ConfigReverseLimit(double reverseLimitPosition) = 0;
virtual void ConfigMaxOutputVoltage(double voltage) = 0;
virtual void ConfigFaultTime(float faultTime) = 0;
virtual float Get() const = 0;
virtual void Set(float value, uint8_t syncGroup = 0) = 0;
virtual void Disable() = 0;
virtual void SetP(double p) = 0;
virtual void SetI(double i) = 0;
virtual void SetD(double d) = 0;
virtual void SetPID(double p, double i, double d) = 0;
virtual double GetP() const = 0;
virtual double GetI() const = 0;
virtual double GetD() const = 0;
virtual float GetBusVoltage() const = 0;
virtual float GetOutputVoltage() const = 0;
virtual float GetOutputCurrent() const = 0;
virtual float GetTemperature() const = 0;
virtual double GetPosition() const = 0;
virtual double GetSpeed() const = 0;
virtual bool GetForwardLimitOK() const = 0;
virtual bool GetReverseLimitOK() const = 0;
virtual uint16_t GetFaults() const = 0;
virtual void SetVoltageRampRate(double rampRate) = 0;
virtual uint32_t GetFirmwareVersion() const = 0;
virtual void ConfigNeutralMode(NeutralMode mode) = 0;
virtual void ConfigEncoderCodesPerRev(uint16_t codesPerRev) = 0;
virtual void ConfigPotentiometerTurns(uint16_t turns) = 0;
virtual void ConfigSoftPositionLimits(double forwardLimitPosition,
double reverseLimitPosition) = 0;
virtual void DisableSoftPositionLimits() = 0;
virtual void ConfigLimitMode(LimitMode mode) = 0;
virtual void ConfigForwardLimit(double forwardLimitPosition) = 0;
virtual void ConfigReverseLimit(double reverseLimitPosition) = 0;
virtual void ConfigMaxOutputVoltage(double voltage) = 0;
virtual void ConfigFaultTime(float faultTime) = 0;
// Hold off on interface until we figure out ControlMode enums.
// virtual void SetControlMode(ControlMode mode) = 0;
// virtual ControlMode GetControlMode() const = 0;
// virtual void SetControlMode(ControlMode mode) = 0;
// virtual ControlMode GetControlMode() const = 0;
};

View File

@@ -25,163 +25,166 @@ class CANTalon : public MotorSafety,
public LiveWindowSendable,
public ITableListener,
public PIDSource,
public PIDInterface
{
public:
public PIDInterface {
public:
enum FeedbackDevice {
QuadEncoder=0,
AnalogPot=2,
AnalogEncoder=3,
EncRising=4,
EncFalling=5
QuadEncoder = 0,
AnalogPot = 2,
AnalogEncoder = 3,
EncRising = 4,
EncFalling = 5
};
enum StatusFrameRate {
StatusFrameRateGeneral=0,
StatusFrameRateFeedback=1,
StatusFrameRateQuadEncoder=2,
StatusFrameRateAnalogTempVbat=3,
StatusFrameRateGeneral = 0,
StatusFrameRateFeedback = 1,
StatusFrameRateQuadEncoder = 2,
StatusFrameRateAnalogTempVbat = 3,
};
explicit CANTalon(int deviceNumber);
explicit CANTalon(int deviceNumber,int controlPeriodMs);
virtual ~CANTalon();
explicit CANTalon(int deviceNumber);
explicit CANTalon(int deviceNumber, int controlPeriodMs);
virtual ~CANTalon();
// PIDOutput interface
virtual void PIDWrite(float output) override;
// PIDOutput interface
virtual void PIDWrite(float output) override;
// PIDSource interface
virtual double PIDGet() const override;
// MotorSafety interface
virtual void SetExpiration(float timeout) override;
virtual float GetExpiration() const override;
virtual bool IsAlive() const override;
virtual void StopMotor() override;
virtual void SetSafetyEnabled(bool enabled) override;
virtual bool IsSafetyEnabled() const override;
virtual void GetDescription(char *desc) const override;
// MotorSafety interface
virtual void SetExpiration(float timeout) override;
virtual float GetExpiration() const override;
virtual bool IsAlive() const override;
virtual void StopMotor() override;
virtual void SetSafetyEnabled(bool enabled) override;
virtual bool IsSafetyEnabled() const override;
virtual void GetDescription(char *desc) const override;
// CANSpeedController interface
virtual float Get() const override;
virtual void Set(float value, uint8_t syncGroup=0) override;
// CANSpeedController interface
virtual float Get() const override;
virtual void Set(float value, uint8_t syncGroup = 0) override;
virtual void Reset() override;
virtual void SetSetpoint(float value) override;
virtual void Disable() override;
virtual void Disable() override;
virtual void EnableControl();
virtual void Enable();
virtual void SetP(double p) override;
virtual void SetI(double i) override;
virtual void SetD(double d) override;
void SetF(double f);
void SetIzone(unsigned iz);
virtual void SetPID(double p, double i, double d) override;
virtual void SetPID(double p, double i, double d, double f);
virtual double GetP() const override;
virtual double GetI() const override;
virtual double GetD() const override;
virtual double GetF() const;
virtual float GetBusVoltage() const override;
virtual float GetOutputVoltage() const override;
virtual float GetOutputCurrent() const override;
virtual float GetTemperature() const override;
void SetPosition(double pos);
virtual double GetPosition() const override;
virtual double GetSpeed() const override;
virtual void SetP(double p) override;
virtual void SetI(double i) override;
virtual void SetD(double d) override;
void SetF(double f);
void SetIzone(unsigned iz);
virtual void SetPID(double p, double i, double d) override;
virtual void SetPID(double p, double i, double d, double f);
virtual double GetP() const override;
virtual double GetI() const override;
virtual double GetD() const override;
virtual double GetF() const;
virtual float GetBusVoltage() const override;
virtual float GetOutputVoltage() const override;
virtual float GetOutputCurrent() const override;
virtual float GetTemperature() const override;
void SetPosition(double pos);
virtual double GetPosition() const override;
virtual double GetSpeed() const override;
virtual int GetClosedLoopError() const;
virtual int GetAnalogIn() const;
virtual int GetAnalogInRaw() const;
virtual int GetAnalogInVel() const;
virtual int GetEncPosition() const;
virtual int GetEncVel() const;
int GetPinStateQuadA() const;
int GetPinStateQuadB() const;
int GetPinStateQuadIdx() const;
int IsFwdLimitSwitchClosed() const;
int IsRevLimitSwitchClosed() const;
int GetNumberOfQuadIdxRises() const;
void SetNumberOfQuadIdxRises(int rises);
virtual bool GetForwardLimitOK() const override;
virtual bool GetReverseLimitOK() const override;
virtual uint16_t GetFaults() const override;
uint16_t GetStickyFaults() const;
void ClearStickyFaults();
virtual void SetVoltageRampRate(double rampRate) override;
virtual uint32_t GetFirmwareVersion() const override;
virtual void ConfigNeutralMode(NeutralMode mode) override;
virtual void ConfigEncoderCodesPerRev(uint16_t codesPerRev) override;
virtual void ConfigPotentiometerTurns(uint16_t turns) override;
virtual void ConfigSoftPositionLimits(double forwardLimitPosition, double reverseLimitPosition) override;
virtual void DisableSoftPositionLimits() override;
virtual void ConfigLimitMode(LimitMode mode) override;
virtual void ConfigForwardLimit(double forwardLimitPosition) override;
virtual void ConfigReverseLimit(double reverseLimitPosition) override;
/**
* Change the fwd limit switch setting to normally open or closed.
* Talon will disable momentarilly if the Talon's current setting
* is dissimilar to the caller's requested setting.
*
* Since Talon saves setting to flash this should only affect
* a given Talon initially during robot install.
*
* @param normallyOpen true for normally open. false for normally closed.
*/
void ConfigFwdLimitSwitchNormallyOpen(bool normallyOpen);
/**
* Change the rev limit switch setting to normally open or closed.
* Talon will disable momentarilly if the Talon's current setting
* is dissimilar to the caller's requested setting.
*
* Since Talon saves setting to flash this should only affect
* a given Talon initially during robot install.
*
* @param normallyOpen true for normally open. false for normally closed.
*/
void ConfigRevLimitSwitchNormallyOpen(bool normallyOpen);
virtual void ConfigMaxOutputVoltage(double voltage) override;
virtual void ConfigFaultTime(float faultTime) override;
virtual void SetControlMode(ControlMode mode);
int GetPinStateQuadA() const;
int GetPinStateQuadB() const;
int GetPinStateQuadIdx() const;
int IsFwdLimitSwitchClosed() const;
int IsRevLimitSwitchClosed() const;
int GetNumberOfQuadIdxRises() const;
void SetNumberOfQuadIdxRises(int rises);
virtual bool GetForwardLimitOK() const override;
virtual bool GetReverseLimitOK() const override;
virtual uint16_t GetFaults() const override;
uint16_t GetStickyFaults() const;
void ClearStickyFaults();
virtual void SetVoltageRampRate(double rampRate) override;
virtual uint32_t GetFirmwareVersion() const override;
virtual void ConfigNeutralMode(NeutralMode mode) override;
virtual void ConfigEncoderCodesPerRev(uint16_t codesPerRev) override;
virtual void ConfigPotentiometerTurns(uint16_t turns) override;
virtual void ConfigSoftPositionLimits(double forwardLimitPosition,
double reverseLimitPosition) override;
virtual void DisableSoftPositionLimits() override;
virtual void ConfigLimitMode(LimitMode mode) override;
virtual void ConfigForwardLimit(double forwardLimitPosition) override;
virtual void ConfigReverseLimit(double reverseLimitPosition) override;
/**
* Change the fwd limit switch setting to normally open or closed.
* Talon will disable momentarilly if the Talon's current setting
* is dissimilar to the caller's requested setting.
*
* Since Talon saves setting to flash this should only affect
* a given Talon initially during robot install.
*
* @param normallyOpen true for normally open. false for normally closed.
*/
void ConfigFwdLimitSwitchNormallyOpen(bool normallyOpen);
/**
* Change the rev limit switch setting to normally open or closed.
* Talon will disable momentarilly if the Talon's current setting
* is dissimilar to the caller's requested setting.
*
* Since Talon saves setting to flash this should only affect
* a given Talon initially during robot install.
*
* @param normallyOpen true for normally open. false for normally closed.
*/
void ConfigRevLimitSwitchNormallyOpen(bool normallyOpen);
virtual void ConfigMaxOutputVoltage(double voltage) override;
virtual void ConfigFaultTime(float faultTime) override;
virtual void SetControlMode(ControlMode mode);
void SetFeedbackDevice(FeedbackDevice device);
void SetStatusFrameRateMs(StatusFrameRate stateFrame, int periodMs);
virtual ControlMode GetControlMode() const;
void SetSensorDirection(bool reverseSensor);
void SetCloseLoopRampRate(double rampRate);
void SelectProfileSlot(int slotIdx);
int GetIzone() const;
int GetIaccum() const;
void ClearIaccum();
int GetBrakeEnableDuringNeutral() const;
void SetStatusFrameRateMs(StatusFrameRate stateFrame, int periodMs);
virtual ControlMode GetControlMode() const;
void SetSensorDirection(bool reverseSensor);
void SetCloseLoopRampRate(double rampRate);
void SelectProfileSlot(int slotIdx);
int GetIzone() const;
int GetIaccum() const;
void ClearIaccum();
int GetBrakeEnableDuringNeutral() const;
bool IsControlEnabled() const;
bool IsEnabled() const override;
double GetSetpoint() const override;
// LiveWindow stuff.
void ValueChanged(ITable* source, const std::string& key, EntryValue value, bool isNew) override;
void UpdateTable() override;
void StartLiveWindowMode() override;
void StopLiveWindowMode() override;
std::string GetSmartDashboardType() const override;
void InitTable(ITable *subTable) override;
ITable * GetTable() const override;
void ValueChanged(ITable *source, const std::string &key, EntryValue value,
bool isNew) override;
void UpdateTable() override;
void StartLiveWindowMode() override;
void StopLiveWindowMode() override;
std::string GetSmartDashboardType() const override;
void InitTable(ITable *subTable) override;
ITable *GetTable() const override;
//SpeedController overrides
// SpeedController overrides
virtual void SetInverted(bool isInverted) override;
virtual bool GetInverted() const override;
private:
virtual bool GetInverted() const override;
private:
// Values for various modes as is sent in the CAN packets for the Talon.
enum TalonControlMode {
kThrottle=0,
kFollowerMode=5,
kVoltageMode=4,
kPositionMode=1,
kSpeedMode=2,
kCurrentMode=3,
kDisabled=15
kThrottle = 0,
kFollowerMode = 5,
kVoltageMode = 4,
kPositionMode = 1,
kSpeedMode = 2,
kCurrentMode = 3,
kDisabled = 15
};
int m_deviceNumber;
CanTalonSRX *m_impl;
MotorSafetyHelper *m_safetyHelper;
int m_profile; // Profile from CANTalon to use. Set to zero until we can actually test this.
int m_deviceNumber;
CanTalonSRX *m_impl;
MotorSafetyHelper *m_safetyHelper;
int m_profile; // Profile from CANTalon to use. Set to zero until we can
// actually test this.
bool m_controlEnabled;
ControlMode m_controlMode;
@@ -198,6 +201,6 @@ private:
void ApplyControlMode(CANSpeedController::ControlMode mode);
// LiveWindow stuff.
ITable *m_table;
ITable *m_table;
bool m_isInverted;
};

View File

@@ -21,7 +21,7 @@
class CameraServer : public ErrorBase {
private:
static constexpr uint16_t kPort = 1180;
static constexpr uint8_t kMagicNumber[] = { 0x01, 0x00, 0x00, 0x00 };
static constexpr uint8_t kMagicNumber[] = {0x01, 0x00, 0x00, 0x00};
static constexpr uint32_t kSize640x480 = 0;
static constexpr uint32_t kSize320x240 = 1;
static constexpr uint32_t kSize160x120 = 2;
@@ -30,7 +30,7 @@ class CameraServer : public ErrorBase {
protected:
CameraServer();
std::shared_ptr<USBCamera> m_camera;
std::thread m_serverThread;
std::thread m_captureThread;
@@ -44,8 +44,10 @@ class CameraServer : public ErrorBase {
void Serve();
void AutoCapture();
void SetImageData(uint8_t* data, unsigned int size, unsigned int start = 0, bool imaqData = false);
void FreeImageData(std::tuple<uint8_t*, unsigned int, unsigned int, bool> imageData);
void SetImageData(uint8_t* data, unsigned int size, unsigned int start = 0,
bool imaqData = false);
void FreeImageData(
std::tuple<uint8_t*, unsigned int, unsigned int, bool> imageData);
struct Request {
uint32_t fps;
@@ -54,12 +56,13 @@ class CameraServer : public ErrorBase {
};
static CameraServer* s_instance;
public:
static CameraServer* GetInstance();
void SetImage(Image const *image);
void SetImage(Image const* image);
void StartAutomaticCapture(char const *cameraName = USBCamera::kDefaultCameraName);
void StartAutomaticCapture(
char const* cameraName = USBCamera::kDefaultCameraName);
/**
* Start automatically capturing images to send to the dashboard.

View File

@@ -15,47 +15,50 @@
/**
* PCM compressor
*/
class Compressor: public SensorBase, public LiveWindowSendable, public ITableListener {
public:
explicit Compressor(uint8_t pcmID);
Compressor();
virtual ~Compressor();
class Compressor : public SensorBase,
public LiveWindowSendable,
public ITableListener {
public:
explicit Compressor(uint8_t pcmID);
Compressor();
virtual ~Compressor();
void Start();
void Stop();
bool Enabled() const;
void Start();
void Stop();
bool Enabled() const;
bool GetPressureSwitchValue() const;
bool GetPressureSwitchValue() const;
float GetCompressorCurrent() const;
float GetCompressorCurrent() const;
void SetClosedLoopControl(bool on);
bool GetClosedLoopControl() const;
void SetClosedLoopControl(bool on);
bool GetClosedLoopControl() const;
bool GetCompressorCurrentTooHighFault() const;
bool GetCompressorCurrentTooHighStickyFault() const;
bool GetCompressorShortedStickyFault() const;
bool GetCompressorShortedFault() const;
bool GetCompressorNotConnectedStickyFault() const;
bool GetCompressorNotConnectedFault() const;
void ClearAllPCMStickyFaults();
bool GetCompressorCurrentTooHighFault() const;
bool GetCompressorCurrentTooHighStickyFault() const;
bool GetCompressorShortedStickyFault() const;
bool GetCompressorShortedFault() const;
bool GetCompressorNotConnectedStickyFault() const;
bool GetCompressorNotConnectedFault() const;
void ClearAllPCMStickyFaults();
void UpdateTable() override;
void StartLiveWindowMode() override;
void StopLiveWindowMode() override;
std::string GetSmartDashboardType() const override;
void InitTable(ITable *subTable) override;
ITable *GetTable() const override;
void ValueChanged(ITable* source, const std::string& key, EntryValue value, bool isNew);
void UpdateTable() override;
void StartLiveWindowMode() override;
void StopLiveWindowMode() override;
std::string GetSmartDashboardType() const override;
void InitTable(ITable *subTable) override;
ITable *GetTable() const override;
void ValueChanged(ITable *source, const std::string &key, EntryValue value,
bool isNew);
protected:
void *m_pcm_pointer;
protected:
void *m_pcm_pointer;
private:
void InitCompressor(uint8_t module);
void SetCompressor(bool on);
private:
void InitCompressor(uint8_t module);
void SetCompressor(bool on);
ITable *m_table;
ITable *m_table;
};
#endif /* Compressor_H_ */

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Copyright (c) FIRST 2011. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -7,24 +8,21 @@
#ifndef __CONTROLLER_POWER_H__
#define __CONTROLLER_POWER_H__
class ControllerPower
{
public:
static double GetInputVoltage();
static double GetInputCurrent();
static double GetVoltage3V3();
static double GetCurrent3V3();
static bool GetEnabled3V3();
static int GetFaultCount3V3();
static double GetVoltage5V();
static double GetCurrent5V();
static bool GetEnabled5V();
static int GetFaultCount5V();
static double GetVoltage6V();
static double GetCurrent6V();
static bool GetEnabled6V();
static int GetFaultCount6V();
class ControllerPower {
public:
static double GetInputVoltage();
static double GetInputCurrent();
static double GetVoltage3V3();
static double GetCurrent3V3();
static bool GetEnabled3V3();
static int GetFaultCount3V3();
static double GetVoltage5V();
static double GetCurrent5V();
static bool GetEnabled5V();
static int GetFaultCount5V();
static double GetVoltage6V();
static double GetCurrent6V();
static bool GetEnabled6V();
static int GetFaultCount6V();
};
#endif

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Copyright (c) FIRST 2008. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -13,82 +14,84 @@
/**
* Class for counting the number of ticks on a digital input channel.
* This is a general purpose class for counting repetitive events. It can return the number
* of counts, the period of the most recent cycle, and detect when the signal being counted
* This is a general purpose class for counting repetitive events. It can return
* the number
* of counts, the period of the most recent cycle, and detect when the signal
* being counted
* has stopped by supplying a maximum cycle time.
*
* All counters will immediately start counting - Reset() them if you need them
* to be zeroed before use.
*/
class Counter : public SensorBase, public CounterBase, public LiveWindowSendable
{
public:
class Counter : public SensorBase,
public CounterBase,
public LiveWindowSendable {
public:
Counter();
explicit Counter(int32_t channel);
explicit Counter(DigitalSource *source);
explicit Counter(DigitalSource &source);
explicit Counter(AnalogTrigger *trigger);
explicit Counter(AnalogTrigger &trigger);
Counter(EncodingType encodingType, DigitalSource *upSource,
DigitalSource *downSource, bool inverted);
virtual ~Counter();
Counter();
explicit Counter(int32_t channel);
explicit Counter(DigitalSource *source);
explicit Counter(DigitalSource &source);
explicit Counter(AnalogTrigger *trigger);
explicit Counter(AnalogTrigger &trigger);
Counter(EncodingType encodingType, DigitalSource *upSource, DigitalSource *downSource,
bool inverted);
virtual ~Counter();
void SetUpSource(int32_t channel);
void SetUpSource(AnalogTrigger *analogTrigger, AnalogTriggerType triggerType);
void SetUpSource(AnalogTrigger &analogTrigger, AnalogTriggerType triggerType);
void SetUpSource(DigitalSource *source);
void SetUpSource(DigitalSource &source);
void SetUpSourceEdge(bool risingEdge, bool fallingEdge);
void ClearUpSource();
void SetUpSource(int32_t channel);
void SetUpSource(AnalogTrigger *analogTrigger, AnalogTriggerType triggerType);
void SetUpSource(AnalogTrigger &analogTrigger, AnalogTriggerType triggerType);
void SetUpSource(DigitalSource *source);
void SetUpSource(DigitalSource &source);
void SetUpSourceEdge(bool risingEdge, bool fallingEdge);
void ClearUpSource();
void SetDownSource(int32_t channel);
void SetDownSource(AnalogTrigger *analogTrigger,
AnalogTriggerType triggerType);
void SetDownSource(AnalogTrigger &analogTrigger,
AnalogTriggerType triggerType);
void SetDownSource(DigitalSource *source);
void SetDownSource(DigitalSource &source);
void SetDownSourceEdge(bool risingEdge, bool fallingEdge);
void ClearDownSource();
void SetDownSource(int32_t channel);
void SetDownSource(AnalogTrigger *analogTrigger, AnalogTriggerType triggerType);
void SetDownSource(AnalogTrigger &analogTrigger, AnalogTriggerType triggerType);
void SetDownSource(DigitalSource *source);
void SetDownSource(DigitalSource &source);
void SetDownSourceEdge(bool risingEdge, bool fallingEdge);
void ClearDownSource();
void SetUpDownCounterMode();
void SetExternalDirectionMode();
void SetSemiPeriodMode(bool highSemiPeriod);
void SetPulseLengthMode(float threshold);
void SetUpDownCounterMode();
void SetExternalDirectionMode();
void SetSemiPeriodMode(bool highSemiPeriod);
void SetPulseLengthMode(float threshold);
void SetReverseDirection(bool reverseDirection);
void SetReverseDirection(bool reverseDirection);
// CounterBase interface
int32_t Get() const override;
void Reset() override;
double GetPeriod() const override;
void SetMaxPeriod(double maxPeriod) override;
void SetUpdateWhenEmpty(bool enabled);
bool GetStopped() const override;
bool GetDirection() const override;
// CounterBase interface
int32_t Get() const override;
void Reset() override;
double GetPeriod() const override;
void SetMaxPeriod(double maxPeriod) override;
void SetUpdateWhenEmpty(bool enabled);
bool GetStopped() const override;
bool GetDirection() const override;
void SetSamplesToAverage(int samplesToAverage);
int GetSamplesToAverage() const;
uint32_t GetFPGAIndex() const { return m_index; }
void SetSamplesToAverage(int samplesToAverage);
int GetSamplesToAverage() const;
uint32_t GetFPGAIndex() const
{
return m_index;
}
void UpdateTable() override;
void StartLiveWindowMode() override;
void StopLiveWindowMode() override;
virtual std::string GetSmartDashboardType() const override;
void InitTable(ITable *subTable) override;
ITable *GetTable() const override;
void UpdateTable() override;
void StartLiveWindowMode() override;
void StopLiveWindowMode() override;
virtual std::string GetSmartDashboardType() const override;
void InitTable(ITable *subTable) override;
ITable * GetTable() const override;
protected:
DigitalSource *m_upSource; ///< What makes the counter count up.
DigitalSource *m_downSource; ///< What makes the counter count down.
void* m_counter; ///< The FPGA counter object.
private:
void InitCounter(Mode mode = kTwoPulse);
protected:
DigitalSource *m_upSource; ///< What makes the counter count up.
DigitalSource *m_downSource; ///< What makes the counter count down.
void *m_counter; ///< The FPGA counter object.
private:
void InitCounter(Mode mode = kTwoPulse);
bool m_allocatedUpSource; ///< Was the upSource allocated locally?
bool m_allocatedDownSource; ///< Was the downSource allocated locally?
uint32_t m_index; ///< The index of this counter.
bool m_allocatedUpSource; ///< Was the upSource allocated locally?
bool m_allocatedDownSource; ///< Was the downSource allocated locally?
uint32_t m_index; ///< The index of this counter.
ITable *m_table;
ITable *m_table;
};

View File

@@ -1,5 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Copyright (c) FIRST 2008. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
@@ -15,21 +16,15 @@
* All counters will immediately start counting - Reset() them if you need them
* to be zeroed before use.
*/
class CounterBase
{
public:
enum EncodingType
{
k1X,
k2X,
k4X
};
class CounterBase {
public:
enum EncodingType { k1X, k2X, k4X };
virtual ~CounterBase() {}
virtual int32_t Get() const = 0;
virtual void Reset() = 0;
virtual double GetPeriod() const = 0;
virtual void SetMaxPeriod(double maxPeriod) = 0;
virtual bool GetStopped() const = 0;
virtual bool GetDirection() const = 0;
virtual ~CounterBase() {}
virtual int32_t Get() const = 0;
virtual void Reset() = 0;
virtual double GetPeriod() const = 0;
virtual void SetMaxPeriod(double maxPeriod) = 0;
virtual bool GetStopped() const = 0;
virtual bool GetDirection() const = 0;
};

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